Java乔晓松-httpURLConnection、URL、httpClient、httpPost、httpGet之代码详解篇

  2021人阅读  评论(4)  收藏  举报
http://blog.csdn.net/qxs965266509/article/details/9072483
[html]  view plain copy
  1. package com.example.lesson09_login;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.net.HttpURLConnection;  
  9. import java.net.MalformedURLException;  
  10. import java.net.ProtocolException;  
  11. import java.net.URL;  
  12. import java.net.URLEncoder;  
  13. import java.util.ArrayList;  
  14. import java.util.List;  
  15.   
  16. import org.apache.http.HttpResponse;  
  17. import org.apache.http.client.ClientProtocolException;  
  18. import org.apache.http.client.HttpClient;  
  19. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  20. import org.apache.http.client.methods.HttpGet;  
  21. import org.apache.http.client.methods.HttpPost;  
  22. import org.apache.http.impl.client.DefaultHttpClient;  
  23. import org.apache.http.message.BasicNameValuePair;  
  24.   
  25. import android.annotation.SuppressLint;  
  26. import android.app.Activity;  
  27. import android.os.Bundle;  
  28. import android.os.Handler;  
  29. import android.os.Message;  
  30. import android.text.TextUtils;  
  31. import android.util.Log;  
  32. import android.view.Menu;  
  33. import android.view.View;  
  34. import android.widget.Button;  
  35. import android.widget.EditText;  
  36. import android.widget.Toast;  
  37.   
  38. @SuppressLint("HandlerLeak")  
  39. public class MainActivity extends Activity {  
  40.   
  41.     public Button btn_get, btn_post;  
  42.     public EditText et_name, et_pass;  
  43.     public NetWorkUtil netWorkUtil;  
  44.     public Handler handler;  
  45.     public static final int GET = 1;  
  46.     public static final int POST = 2;  
  47.     public String name, pass, content;  
  48.     public String path = "http://172.22.64.18:8080/lesson09_login/csdn/UserAction_login.action";  
  49.   
  50.     @Override  
  51.     protected void onCreate(Bundle savedInstanceState) {  
  52.         super.onCreate(savedInstanceState);  
  53.         setContentView(R.layout.activity_main);  
  54.   
  55.         btn_get = (Button) findViewById(R.id.btn_get);  
  56.         btn_post = (Button) findViewById(R.id.btn_post);  
  57.   
  58.         et_name = (EditText) findViewById(R.id.et_name);  
  59.         et_pass = (EditText) findViewById(R.id.et_pass);  
  60.   
  61.         netWorkUtil = new NetWorkUtil(this);  
  62.   
  63.         handler = new Handler() {  
  64.             @Override  
  65.             public void handleMessage(Message msg) {  
  66.                 super.handleMessage(msg);  
  67.                 switch (msg.what) {  
  68.                 case GET:  
  69.                     Toast.makeText(MainActivity.this, "GET请求成功++++++++++",  
  70.                             Toast.LENGTH_LONG).show();  
  71.                     Log.v("MainActity", content);  
  72.                     break;  
  73.                 case POST:  
  74.                     Toast.makeText(MainActivity.this, "POST请求成功----------",  
  75.                             Toast.LENGTH_LONG).show();  
  76.                     Log.v("MainActity", content);  
  77.                     break;  
  78.   
  79.                 default:  
  80.                     break;  
  81.                 }  
  82.             }  
  83.         };  
  84.     }  
  85.   
  86.     @Override  
  87.     public boolean onCreateOptionsMenu(Menu menu) {  
  88.         // Inflate the menu; this adds items to the action bar if it is present.  
  89.         getMenuInflater().inflate(R.menu.main, menu);  
  90.         return true;  
  91.     }  
  92.   
  93.     public void sendGet(View v) {  
  94.         if (!isEmpty()) {  
  95.             Toast.makeText(MainActivity.this, "用户名或密码不能为空...",  
  96.                     Toast.LENGTH_LONG).show();  
  97.         } else {  
  98.             boolean flag = netWorkUtil.setNetWork();  
  99.             if (flag) {  
  100.                 new Thread(new Runnable() {  
  101.   
  102.                     @Override  
  103.                     public void run() {  
  104.                         name = et_name.getText().toString();  
  105.                         pass = et_pass.getText().toString();  
  106.                         // sendGetRequest(path, name, pass);  
  107.                         sendGetClient(path, name, pass);  
  108.                         handler.sendEmptyMessage(GET);  
  109.                     }  
  110.   
  111.                 }).start();  
  112.             }  
  113.         }  
  114.     }  
  115.   
  116.     public void sendPost(View v) {  
  117.         if (!isEmpty()) {  
  118.             Toast.makeText(MainActivity.this, "用户名或密码不能为空...",  
  119.                     Toast.LENGTH_LONG).show();  
  120.         } else {  
  121.             boolean flag = netWorkUtil.setNetWork();  
  122.             if (flag) {  
  123.                 new Thread(new Runnable() {  
  124.   
  125.                     @Override  
  126.                     public void run() {  
  127.                         name = et_name.getText().toString();  
  128.                         pass = et_pass.getText().toString();  
  129.                         // sendPostRequest(path, name, pass);  
  130.                         sendPostClient(path, name, pass);  
  131.                         handler.sendEmptyMessage(POST);  
  132.                     }  
  133.   
  134.                 }).start();  
  135.             }  
  136.         }  
  137.     }  
  138.   
  139.     public boolean isEmpty() {  
  140.         boolean flag = false;  
  141.         if (TextUtils.isEmpty(et_name.getText().toString())  
  142.                 || TextUtils.isEmpty(et_pass.getText().toString())) {  
  143.             flag = false;  
  144.         } else {  
  145.             flag = true;  
  146.         }  
  147.         return flag;  
  148.     }  
  149.   
  150.     @SuppressWarnings("unused")  
  151.     private void sendGetRequest(String path, String name, String pass) {  
  152.         String str = path + "?user.name=" + name + "&user.pass=" + pass;  
  153.         try {  
  154.             URL url = new URL(str);  
  155.             HttpURLConnection httpURLConnection = (HttpURLConnection) url  
  156.                     .openConnection();  
  157.             httpURLConnection.setConnectTimeout(5000);  
  158.             httpURLConnection.setRequestMethod("GET");  
  159.             if (httpURLConnection.getResponseCode() == 200) {  
  160.                 InputStream is = httpURLConnection.getInputStream();  
  161.                 ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  162.                 byte[] buf = new byte[1024];  
  163.                 int len = 0;  
  164.                 while ((len = is.read(buf)) != -1) {  
  165.                     bos.write(buf, 0, len);  
  166.                 }  
  167.                 byte[] data = bos.toByteArray();  
  168.                 bos.flush();  
  169.                 bos.close();  
  170.                 is.close();  
  171.                 content = new String(data);  
  172.                 if (content.contains("gb2312")) {  
  173.                     content = new String(data, "gb2312");  
  174.                 }  
  175.             }  
  176.             httpURLConnection.disconnect();  
  177.         } catch (MalformedURLException e) {  
  178.             e.printStackTrace();  
  179.         } catch (ProtocolException e) {  
  180.             e.printStackTrace();  
  181.         } catch (IOException e) {  
  182.             e.printStackTrace();  
  183.         }  
  184.     }  
  185.   
  186.     @SuppressWarnings("unused")  
  187.     private void sendPostRequest(String path, String name, String pass) {  
  188.   
  189.         try {  
  190.             String data = "user.name=" + name + "&user.pass=" + pass;  
  191.             URL url = new URL(path);  
  192.             HttpURLConnection httpURLConnection = (HttpURLConnection) url  
  193.                     .openConnection();  
  194.             httpURLConnection.setConnectTimeout(5000);  
  195.             httpURLConnection.setRequestMethod("POST");  
  196.             httpURLConnection.setDoOutput(true);  
  197.             httpURLConnection.setRequestProperty("Content-Type",  
  198.                     "application/x-www-form-urlencoded");  
  199.             httpURLConnection.setRequestProperty("Content-Length",  
  200.                     data.length() + "");  
  201.             OutputStream os = httpURLConnection.getOutputStream();  
  202.             byte[] buf = data.getBytes();  
  203.             os.write(buf);  
  204.             os.flush();  
  205.             os.close();  
  206.             if (httpURLConnection.getResponseCode() == 200) {  
  207.                 InputStream is = httpURLConnection.getInputStream();  
  208.                 ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  209.                 byte[] buf1 = new byte[1024];  
  210.                 int len = 0;  
  211.                 while ((len = is.read(buf1)) != -1) {  
  212.                     bos.write(buf1, 0, len);  
  213.                 }  
  214.                 byte[] data1 = bos.toByteArray();  
  215.                 bos.flush();  
  216.                 bos.close();  
  217.                 is.close();  
  218.                 content = new String(data1);  
  219.             }  
  220.             httpURLConnection.disconnect();  
  221.   
  222.         } catch (MalformedURLException e) {  
  223.             e.printStackTrace();  
  224.         } catch (IOException e) {  
  225.             e.printStackTrace();  
  226.         }  
  227.   
  228.     }  
  229.   
  230.     public void sendGetClient(String path, String name, String pass) {  
  231.         try {  
  232.             String uri = path + "?user.name="  
  233.                     + URLEncoder.encode(name, "UTF-8") + "&user.pass="  
  234.                     + URLEncoder.encode(pass, "UTF-8");  
  235.             HttpClient httpClient = new DefaultHttpClient();  
  236.             HttpGet httpGet = new HttpGet(uri);  
  237.   
  238.             HttpResponse httpResponse = httpClient.execute(httpGet);  
  239.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  240.                 InputStream is = httpResponse.getEntity().getContent();  
  241.                 content = StringTool.isContent(is);  
  242.             }  
  243.         } catch (UnsupportedEncodingException e) {  
  244.             e.printStackTrace();  
  245.         } catch (ClientProtocolException e) {  
  246.             e.printStackTrace();  
  247.         } catch (IOException e) {  
  248.             e.printStackTrace();  
  249.         }  
  250.     }  
  251.   
  252.     @SuppressWarnings("unused")  
  253.     public void sendPostClient(String path, String name, String pass) {  
  254.         HttpClient httpClient = new DefaultHttpClient();  
  255.         HttpPost httpPost = new HttpPost(path);  
  256.         List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();  
  257.         parameters.add(new BasicNameValuePair("user.name", name));  
  258.         parameters.add(new BasicNameValuePair("user.pass", pass));  
  259.         UrlEncodedFormEntity entity = null;  
  260.         try {  
  261.             entity = new UrlEncodedFormEntity(parameters, "UTF-8");  
  262.             HttpResponse httpResponse = httpClient.execute(httpPost);  
  263.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  264.                 InputStream is = httpResponse.getEntity().getContent();  
  265.                 content = StringTool.isContent(is);  
  266.             }  
  267.         } catch (UnsupportedEncodingException e) {  
  268.             e.printStackTrace();  
  269.         } catch (ClientProtocolException e) {  
  270.             e.printStackTrace();  
  271.         } catch (IOException e) {  
  272.             e.printStackTrace();  
  273.         }  
  274.     }  
  275. }  


 

 

[html]  view plain copy
  1. package com.example.lesson09_login;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6.   
  7. /**  
  8.  * 2013-6-10 上午9:33:34  
  9.  *   
  10.  * @author 乔晓松  
  11.  */  
  12. public class StringTool {  
  13.   
  14.     public static String isContent(InputStream is) {  
  15.         String content = null;  
  16.         try {  
  17.             ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  18.             byte[] buf = new byte[1024];  
  19.             int len = 0;  
  20.             while ((len = is.read(buf)) != -1) {  
  21.                 bos.write(buf, 0, len);  
  22.             }  
  23.             byte[] data = bos.toByteArray();  
  24.             bos.flush();  
  25.             bos.close();  
  26.             is.close();  
  27.             content = new String(data);  
  28.         } catch (IOException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.         return content;  
  32.     }  
  33. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值