String path = "http://192.168.22.73:8080/web/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";URL url = new URL(path);//打开一个url连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置conn 的参数conn.setRequestMethod("GET");conn.setConnectTimeout(5000);//获取服务器返回的状态码int code = conn.getResponseCode();if (code == 200) { //200 请求服务器资源全部返回成功 //206 请求部分服务器资源返回成功InputStream inputStream = conn.getInputStream(); //获取服务器返回的数据//就是服务器返回数据 ---String content = StreamTools.readStream(inputStream);//toast 也不可以在子线程更新showToast(content);
注:StreamTool是自己编写的一个工具类,目的是将输入流转换为字符串 }
//post和get方式登录的区别 (1)**************路径不同String path = "http://192.168.22.73:8080/web/LoginServlet";try {URL url = new URL(path);//打开一个url连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置conn 的参数conn.setRequestMethod("POST");conn.setConnectTimeout(5000);//获取服务器返回的状态码//post和get方式登录的区别 (2)**************要设置头信息 Content-Type Content-LengthString data="username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", data.getBytes().length+"");//post和get方式登录的区别 (3)************** 以流的形式把数据写给服务器conn.setDoOutput(true); //设置一个标记 允许输出conn.getOutputStream().write(data.getBytes());int code = conn.getResponseCode();if (code == 200) { //200 请求服务器资源全部返回成功 //206 请求部分服务器资源返回成功InputStream inputStream = conn.getInputStream(); //获取服务器返回的数据//就是服务器返回数据 ---String content = StreamTools.readStream(inputStream);//toast 也不可以在子线程更新showToast(content);}
注:URLEncoder.encode()This class is used to encode a string using the format required byapplication/x-www-form-urlencodedMIME content type.
//显示一个toastpublic void showToast(final String content){runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(getApplicationContext(), content, 1).show();}});}}
public class StreamTools {/*** 读取流* @param in* @return* @throws IOException*/public static String readStream(InputStream in) throws IOException{//定义一个内存输入流 bos 流不用关闭 关闭无效ByteArrayOutputStream bos = new ByteArrayOutputStream();int len = -1;byte buffer[] = new byte[1024];while((len = in.read(buffer))!=-1){bos.write(buffer, 0, len);};in.close();return new String(bos.toByteArray(),"gbk");}}
原文:http://www.cnblogs.com/candledragle/p/4212277.html