安卓doGet( )和doPost()

doGet请求方式:
        
  1. String path = "http://192.168.22.73:8080/web/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
  2. URL url = new URL(path);
  3. //打开一个url连接
  4. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  5. //设置conn 的参数
  6. conn.setRequestMethod("GET");
  7. conn.setConnectTimeout(5000);
  8. //获取服务器返回的状态码
  9. int code = conn.getResponseCode();
  10. if (code == 200) { //200 请求服务器资源全部返回成功 //206 请求部分服务器资源返回成功
  11. InputStream inputStream = conn.getInputStream(); //获取服务器返回的数据
  12. //就是服务器返回数据 ---
  13. String content = StreamTools.readStream(inputStream);
  14. //toast 也不可以在子线程更新
  15. showToast(content);


  16. 注:StreamTool是自己编写的一个工具类,目的是将输入流转换为字符串
    }

doPost请求方式:
  1. //post和get方式登录的区别 (1)**************路径不同
  2. String path = "http://192.168.22.73:8080/web/LoginServlet";
  3. try {
  4. URL url = new URL(path);
  5. //打开一个url连接
  6. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  7. //设置conn 的参数
  8. conn.setRequestMethod("POST");
  9. conn.setConnectTimeout(5000);
  10. //获取服务器返回的状态码
  11. //post和get方式登录的区别 (2)**************要设置头信息 Content-Type Content-Length
  12. String data="username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
  13. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  14. conn.setRequestProperty("Content-Length", data.getBytes().length+"");
  15. //post和get方式登录的区别 (3)************** 以流的形式把数据写给服务器
  16. conn.setDoOutput(true); //设置一个标记 允许输出
  17. conn.getOutputStream().write(data.getBytes());
  18. int code = conn.getResponseCode();
  19. if (code == 200) { //200 请求服务器资源全部返回成功 //206 请求部分服务器资源返回成功
  20. InputStream inputStream = conn.getInputStream(); //获取服务器返回的数据
  21. //就是服务器返回数据 ---
  22. String content = StreamTools.readStream(inputStream);
  23. //toast 也不可以在子线程更新
  24. showToast(content);
  25. }
    注:URLEncoder.encode()This class is used to encode a string using the format required by application/x-www-form-urlencoded MIME content type.


用到的方法:
  1. //显示一个toast
  2. public void showToast(final String content){
  3. runOnUiThread(new Runnable() {
  4. @Override
  5. public void run() {
  6. Toast.makeText(getApplicationContext(), content, 1).show();
  7. }
  8. });
  9. }
  10. }

流转字符串
  1. public class StreamTools {
  2. /**
  3. * 读取流
  4. * @param in
  5. * @return
  6. * @throws IOException
  7. */
  8. public static String readStream(InputStream in) throws IOException{
  9. //定义一个内存输入流 bos 流不用关闭 关闭无效
  10. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  11. int len = -1;
  12. byte buffer[] = new byte[1024];
  13. while((len = in.read(buffer))!=-1){
  14. bos.write(buffer, 0, len);
  15. };
  16. in.close();
  17. return new String(bos.toByteArray(),"gbk");
  18. }
  19. }

        




posted @ 2015-01-09 00:21  就不呵呵呵  阅读(305)  评论(0编辑  收藏  举报