URLConnection和HTTPClient的比较

来源:互联网 发布:哪些端口不是敏感端口 编辑:程序博客网 时间:2024/04/20 02:33

A Comparison of java.net.URLConnection and HTTPClient

Since java.net.URLConnection and HTTPClient have overlappingfunctionalities, the question arises of why would you use HTTPClient.Here are a few of the capabilites and tradeoffs.

1.概念

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。

除此之外,在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。

2.区别

HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,

HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。

3.案例

URLConnection

[java] view plaincopy
  1. String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do";   
  2. URL url;   
  3. HttpURLConnection uRLConnection;   
  4. public UrlConnectionToServer(){   
  5.   
  6. }  
  7. //向服务器发送get请求  
  8. public String doGet(String username,String password){   
  9. String getUrl = urlAddress + "?username="+username+"&password="+password;   
  10. try {   
  11. url = new URL(getUrl);   
  12. uRLConnection = (HttpURLConnection)url.openConnection();   
  13. InputStream is = uRLConnection.getInputStream();   
  14. BufferedReader br = new BufferedReader(new InputStreamReader(is));   
  15. String response = "";   
  16. String readLine = null;   
  17. while((readLine =br.readLine()) != null){   
  18. //response = br.readLine();   
  19. response = response + readLine;   
  20. }   
  21. is.close();   
  22. br.close();   
  23. uRLConnection.disconnect();   
  24. return response;   
  25. catch (MalformedURLException e) {   
  26. e.printStackTrace();   
  27. returnnull;   
  28. catch (IOException e) {   
  29. e.printStackTrace();   
  30. returnnull;   
  31. }   
  32. }   
  33.    
  34. //向服务器发送post请求  
  35. public String doPost(String username,String password){   
  36. try {   
  37. url = new URL(urlAddress);   
  38. uRLConnection = (HttpURLConnection)url.openConnection();   
  39. uRLConnection.setDoInput(true);   
  40. uRLConnection.setDoOutput(true);   
  41. uRLConnection.setRequestMethod("POST");   
  42. uRLConnection.setUseCaches(false);   
  43. uRLConnection.setInstanceFollowRedirects(false);   
  44. uRLConnection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");   
  45. uRLConnection.connect();   
  46.   
  47. DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());   
  48. String content = "username="+username+"&password="+password;   
  49. out.writeBytes(content);   
  50. out.flush();   
  51. out.close();   
  52.   
  53. InputStream is = uRLConnection.getInputStream();   
  54. BufferedReader br = new BufferedReader(new InputStreamReader(is));   
  55. String response = "";   
  56. String readLine = null;   
  57. while((readLine =br.readLine()) != null){   
  58. //response = br.readLine();   
  59. response = response + readLine;   
  60. }   
  61. is.close();   
  62. br.close();   
  63. uRLConnection.disconnect();   
  64. return response;   
  65. catch (MalformedURLException e) {   
  66. e.printStackTrace();   
  67. returnnull;   
  68. catch (IOException e) {   
  69. e.printStackTrace();   
  70. returnnull;   
  71. }   
  72. }  


 

HTTPClient

[java] view plaincopy
  1. String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";   
  2. public HttpClientServer(){   
  3.   
  4. }   
  5.   
  6. public String doGet(String username,String password){   
  7. String getUrl = urlAddress + "?username="+username+"&password="+password;   
  8. HttpGet httpGet = new HttpGet(getUrl);   
  9. HttpParams hp = httpGet.getParams();   
  10. hp.getParameter("true");   
  11. //hp.   
  12. //httpGet.setp   
  13. HttpClient hc = new DefaultHttpClient();   
  14. try {   
  15. HttpResponse ht = hc.execute(httpGet);   
  16. if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){   
  17. HttpEntity he = ht.getEntity();   
  18. InputStream is = he.getContent();   
  19. BufferedReader br = new BufferedReader(new InputStreamReader(is));   
  20. String response = "";   
  21. String readLine = null;   
  22. while((readLine =br.readLine()) != null){   
  23. //response = br.readLine();   
  24. response = response + readLine;   
  25. }   
  26. is.close();   
  27. br.close();   
  28.   
  29. //String str = EntityUtils.toString(he);   
  30. System.out.println("========="+response);   
  31. return response;   
  32. }else{   
  33. return "error";   
  34. }   
  35. catch (ClientProtocolException e) {   
  36. // TODO Auto-generated catch block   
  37. e.printStackTrace();   
  38. return "exception";   
  39. catch (IOException e) {   
  40. // TODO Auto-generated catch block   
  41. e.printStackTrace();   
  42. return "exception";   
  43. }   
  44. }   
  45.   
  46. public String doPost(String username,String password){   
  47. //String getUrl = urlAddress + "?username="+username+"&password="+password;   
  48. HttpPost httpPost = new HttpPost(urlAddress);   
  49. List params = new ArrayList();   
  50. NameValuePair pair1 = new BasicNameValuePair("username", username);   
  51. NameValuePair pair2 = new BasicNameValuePair("password", password);   
  52. params.add(pair1);   
  53. params.add(pair2);   
  54.   
  55. HttpEntity he;   
  56. try {   
  57. he = new UrlEncodedFormEntity(params, "gbk");   
  58. httpPost.setEntity(he);   
  59.   
  60. catch (UnsupportedEncodingException e1) {   
  61. // TODO Auto-generated catch block   
  62. e1.printStackTrace();   
  63. }   
  64.   
  65. HttpClient hc = new DefaultHttpClient();   
  66. try {   
  67. HttpResponse ht = hc.execute(httpPost);   
  68. //连接成功   
  69. if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){   
  70. HttpEntity het = ht.getEntity();   
  71. InputStream is = het.getContent();   
  72. BufferedReader br = new BufferedReader(new InputStreamReader(is));   
  73. String response = "";   
  74. String readLine = null;   
  75. while((readLine =br.readLine()) != null){   
  76. //response = br.readLine();   
  77. response = response + readLine;   
  78. }   
  79. is.close();   
  80. br.close();   
  81.   
  82. //String str = EntityUtils.toString(he);   
  83. System.out.println("=========&&"+response);   
  84. return response;   
  85. }else{   
  86. return "error";   
  87. }   
  88. catch (ClientProtocolException e) {   
  89. // TODO Auto-generated catch block   
  90. e.printStackTrace();   
  91. return "exception";   
  92. catch (IOException e) {   
  93. // TODO Auto-generated catch block   
  94. e.printStackTrace();   
  95. return "exception";   
  96. }   
  97. }  


 

servlet端json转化:

[java] view plaincopy
  1. resp.setContentType("text/json");   
  2. resp.setCharacterEncoding("UTF-8");   
  3. toDo = new ToDo();   
  4. List<UserBean> list = new ArrayList<UserBean>();   
  5. list = toDo.queryUsers(mySession);   
  6. String body;   
  7.   
  8. //设定JSON   
  9. JSONArray array = new JSONArray();   
  10. for(UserBean bean : list)   
  11. {   
  12. JSONObject obj = new JSONObject();   
  13. try  
  14. {   
  15. obj.put("username", bean.getUserName());   
  16. obj.put("password", bean.getPassWord());   
  17. }catch(Exception e){}   
  18. array.add(obj);   
  19. }   
  20. pw.write(array.toString());   
  21. System.out.println(array.toString());  


 

android端接收:

[java] view plaincopy
  1. String urlAddress = "http://192.168.1.102:8080/qualityserver/result.do";   
  2. String body =   
  3. getContent(urlAddress);   
  4. JSONArray array = new JSONArray(body);   
  5. for(int i=0;i<array.length();i++)   
  6. {   
  7. obj = array.getJSONObject(i);   
  8. sb.append("用户名:").append(obj.getString("username")).append("\t");   
  9. sb.append("密码:").append(obj.getString("password")).append("\n");   
  10.   
  11. HashMap<String, Object> map = new HashMap<String, Object>();   
  12. try {   
  13. userName = obj.getString("username");   
  14. passWord = obj.getString("password");   
  15. catch (JSONException e) {   
  16. e.printStackTrace();   
  17. }   
  18. map.put("username", userName);   
  19. map.put("password", passWord);   
  20. listItem.add(map);   
  21.   
  22. }   
  23.   
  24. catch (Exception e) {   
  25. // TODO Auto-generated catch block   
  26. e.printStackTrace();   
  27. }   
  28.   
  29. if(sb!=null)   
  30. {   
  31. showResult.setText("用户名和密码信息:");   
  32. showResult.setTextSize(20);   
  33. else  
  34. extracted();   
  35.   
  36. //设置adapter   
  37. SimpleAdapter simple = new SimpleAdapter(this,listItem,   
  38. android.R.layout.simple_list_item_2,   
  39. new String[]{"username","password"},   
  40. newint[]{android.R.id.text1,android.R.id.text2});   
  41. listResult.setAdapter(simple);   
  42.   
  43. listResult.setOnItemClickListener(new OnItemClickListener() {   
  44. @Override   
  45. publicvoid onItemClick(AdapterView<?> parent, View view,   
  46. int position, long id) {   
  47. int positionId = (int) (id+1);   
  48. Toast.makeText(MainActivity.this"ID:"+positionId, Toast.LENGTH_LONG).show();   
  49.   
  50. }   
  51. });   
  52. }   
  53. privatevoid extracted() {   
  54. showResult.setText("没有有效的数据!");   
  55. }   
  56. //和服务器连接   
  57. private String getContent(String url)throws Exception{   
  58. StringBuilder sb = new StringBuilder();   
  59. HttpClient client =new DefaultHttpClient();   
  60. HttpParams httpParams =client.getParams();   
  61.   
  62. HttpConnectionParams.setConnectionTimeout(httpParams, 3000);   
  63. HttpConnectionParams.setSoTimeout(httpParams, 5000);   
  64. HttpResponse response = client.execute(new HttpGet(url));   
  65. HttpEntity entity =response.getEntity();   
  66.   
  67. if(entity !=null){   
  68. BufferedReader reader = new BufferedReader(new InputStreamReader   
  69. (entity.getContent(),"UTF-8"),8192);   
  70. String line =null;   
  71. while ((line= reader.readLine())!=null){   
  72. sb.append(line +"\n");   
  73. }   
  74. reader.close();   
  75. }   
  76. return sb.toString();   
  77. }  


 


 

URLConnection

HTTPClient

Proxies and SOCKS

Full support in Netscape browser, appletviewer, and applications (SOCKS: Version 4 only); no additional limitations from security policies.

Full support (SOCKS: Version 4 and 5); limited in applets however by security policies; in Netscape can't pick up the settings from the browser.

Authorization

Full support for Basic Authorization in Netscape (can use info given by the user for normal accesses outside of the applet); no support in appletviewer or applications.

Full support everywhere; however cannot access previously given info from Netscape, thereby possibly requesting the user to enter info (s)he has already given for a previous access. Also, you can add/implement additional authentication mechanisms yourself.

Methods

Only has GET and POST.

Has HEAD, GET, POST, PUT, DELETE, TRACE and OPTIONS, plus any arbitrary method.

Headers

Currently you can only set any request headers if you are doing a POST under Netscape; for GETs and the JDK you can't set any headers.
Under Netscape 3.0 you can read headers only if the resource was returned with a Content-length header; if no Content-length header was returned, or under previous versions of Netscape, or using the JDK no headers can be read.

Allows any arbitrary headers to be sent and received.

Automatic Redirection Handling

Yes.

Yes (as allowed by the HTTP/1.1 spec).

Persistent Connections

No support currently in JDK; under Netscape uses HTTP/1.0 Keep-Alive's.

Supports HTTP/1.0 Keep-Alive's and HTTP/1.1 persistence.

Pipelining of Requests

No.

Yes.

Can handle protocols other than HTTP

Theoretically; however only http is currently implemented.

No.

Can do HTTP over SSL (https)

Under Netscape, yes. Using Appletviewer or in an application, no.

No (not yet).

Source code available

No.

Yes.

 

 

转自:http://blog.sina.com.cn/s/blog_6610da3901012doz.html

原创粉丝点击