URLConnection和HTTPClient的比较

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

 String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do"; 
URL url; 
HttpURLConnection uRLConnection; 
 public UrlConnectionToServer(){ 
 
}
 //向服务器发送get请求
 public String doGet(String username,String password){ 
String getUrl = urlAddress + "?username="+username+"&password="+password; 
 try { 
url = new URL(getUrl); 
uRLConnection = (HttpURLConnection)url.openConnection(); 
InputStream is = uRLConnection.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
String response = ""; 
String readLine = null; 
 while((readLine =br.readLine()) != null){ 
 //response = br.readLine(); 
response = response + readLine; } is.close(); br.close(); uRLConnection.disconnect(); return response; } catch (MalformedURLException e) { e.printStackTrace(); returnnull; } catch (IOException e) { e.printStackTrace(); returnnull; } }  
//向服务器发送post请求
 public String doPost(String username,String password){ 
 try { 
url = new URL(urlAddress); 
uRLConnection = (HttpURLConnection)url.openConnection(); 
uRLConnection.setDoInput(true); 
uRLConnection.setDoOutput(true); 
uRLConnection.setRequestMethod("POST"); 
uRLConnection.setUseCaches(false); 
uRLConnection.setInstanceFollowRedirects(false); 
uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
uRLConnection.connect(); 
 
DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream()); 
String content = "username="+username+"&password="+password; 
out.writeBytes(content);  
out.flush(); 
out.close(); 
 
InputStream is = uRLConnection.getInputStream(); 
BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
String response = ""; 
String readLine = null; 
 while((readLine =br.readLine()) != null){ 
 //response = br.readLine(); 
response = response + readLine; } is.close(); br.close(); uRLConnection.disconnect(); return response; } catch (MalformedURLException e) { e.printStackTrace(); returnnull; } catch (IOException e) { e.printStackTrace(); returnnull; } }

HTTPClient

String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do"; 
 public HttpClientServer(){ 
 
} 
 
 public String doGet(String username,String password){ 
String getUrl = urlAddress + "?username="+username+"&password="+password; 
HttpGet httpGet = new HttpGet(getUrl); 
HttpParams hp = httpGet.getParams(); 
hp.getParameter("true"); 
 //hp. 
//httpGet.setp
HttpClient hc = new DefaultHttpClient(); try { HttpResponse ht = hc.execute(httpGet); if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity he = ht.getEntity(); InputStream is = he.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String response = ""; String readLine = null; while((readLine =br.readLine()) != null){ //response = br.readLine();
response = response + readLine; } is.close(); br.close(); //String str = EntityUtils.toString(he);
System.out.println("========="+response); return response; }else{ return "error"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block
e.printStackTrace(); return "exception"; } catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); return "exception"; } } public String doPost(String username,String password){ //String getUrl = urlAddress + "?username="+username+"&password="+password;
HttpPost httpPost = new HttpPost(urlAddress); List params = new ArrayList(); NameValuePair pair1 = new BasicNameValuePair("username", username); NameValuePair pair2 = new BasicNameValuePair("password", password); params.add(pair1); params.add(pair2); HttpEntity he; try { he = new UrlEncodedFormEntity(params, "gbk"); httpPost.setEntity(he); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block
e1.printStackTrace(); } HttpClient hc = new DefaultHttpClient(); try { HttpResponse ht = hc.execute(httpPost); //连接成功
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity het = ht.getEntity(); InputStream is = het.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String response = ""; String readLine = null; while((readLine =br.readLine()) != null){ //response = br.readLine();
response = response + readLine; } is.close(); br.close(); //String str = EntityUtils.toString(he);
System.out.println("=========&&"+response); return response; }else{ return "error"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block
e.printStackTrace(); return "exception"; } catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); return "exception"; } }

servlet端json转化: 

 resp.setContentType("text/json"); 
resp.setCharacterEncoding("UTF-8"); 
toDo = new ToDo(); 
List<UserBean> list = new ArrayList<UserBean>(); 
list = toDo.queryUsers(mySession); 
String body; 
 
 //设定JSON 
JSONArray array = new JSONArray(); for(UserBean bean : list) { JSONObject obj = new JSONObject(); try { obj.put("username", bean.getUserName()); obj.put("password", bean.getPassWord()); }catch(Exception e){} array.add(obj); } pw.write(array.toString()); System.out.println(array.toString());

android端接收:

String urlAddress = "http://192.168.1.102:8080/qualityserver/result.do"; 
String body = 
getContent(urlAddress); 
JSONArray array = new JSONArray(body); 
 for(int i=0;i<array.length();i++) 
{ 
obj = array.getJSONObject(i); 
sb.append("用户名:").append(obj.getString("username")).append("\t"); 
sb.append("密码:").append(obj.getString("password")).append("\n"); 
 
HashMap<String, Object> map = new HashMap<String, Object>(); 
 try { 
userName = obj.getString("username"); 
passWord = obj.getString("password"); 
} catch (JSONException e) { 
e.printStackTrace(); 
} 
map.put("username", userName); 
map.put("password", passWord); 
listItem.add(map); 
 
} 
 
} catch (Exception e) { 
 // TODO Auto-generated catch block 
e.printStackTrace(); } if(sb!=null) { showResult.setText("用户名和密码信息:"); showResult.setTextSize(20); } else extracted(); //设置adapter
SimpleAdapter simple = new SimpleAdapter(this,listItem, android.R.layout.simple_list_item_2, new String[]{"username","password"}, newint[]{android.R.id.text1,android.R.id.text2}); listResult.setAdapter(simple); listResult.setOnItemClickListener(new OnItemClickListener() { @Override publicvoid onItemClick(AdapterView<?> parent, View view, int position, long id) { int positionId = (int) (id+1); Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show(); } }); } privatevoid extracted() { showResult.setText("没有有效的数据!"); } //和服务器连接
private String getContent(String url)throws Exception{ StringBuilder sb = new StringBuilder(); HttpClient client =new DefaultHttpClient(); HttpParams httpParams =client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 3000); HttpConnectionParams.setSoTimeout(httpParams, 5000); HttpResponse response = client.execute(new HttpGet(url)); HttpEntity entity =response.getEntity(); if(entity !=null){ BufferedReader reader = new BufferedReader(new InputStreamReader (entity.getContent(),"UTF-8"),8192); String line =null; while ((line= reader.readLine())!=null){ sb.append(line +"\n"); } reader.close(); } return sb.toString(); }
 

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 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。 

       HttpURLConnection是java的标准类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:

 

  • int getResponseCode():获取服务器的响应代码。
  • String getResponseMessage():获取服务器的响应消息。
  • String getResponseMethod():获取发送请求的方法。
  • void setRequestMethod(String method):设置发送请求的方法。

       在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。

       为了更好地处理向Web站点请求,包括处理Session、Cookie等细节问题,Apache开源组织提供了一个HttpClient项目,看它的名称就知道,它是一个简单的HTTP客户端(并不是浏览器),可以用于发送HTTP请求,接收HTTP响应。但不会缓存服务器的响应,不能执行HTML页面中嵌入的Javascript代码;也不会对页面内容进行任何解析、处理。

       简单来说,HttpClient 就是一个增强版的HttpURLConnection,HttpURLConnection 可以做的事情HttpClient 全部可以做;HttpURLConnection 没 有提供的有些功能,HttpClient 也提供了,但它只是关注于如何发送请求、接收
响应,以及管理HTTP连接。
       使用HttpClient 发送请求、接收响应很简单,只要如下几步即可。

  1. 创建HttpClient对象。
  2. 如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,执行该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
       另外,Android已经成功地集成了HttpClient, 这意味着开发人员可以直接在Android 应用中使用Httpclient来访问提交请求、接收响应。
       比如一个Android应用需要向指定页面发送请求,但该页面并不是一个简单的页面,只有当用户已经登录,而且登录用户的用户名有效时才可访问该页面。如果使用HttpURLConnection 来访问这个被保护的页面,那么需要处理的细节就太复杂了。
       其实访问Web应用中被保护的页面,使用浏览器则十分简单,用户通过系统提供的登录页面登录系统,浏览器会负责维护与服务器之间的Sesion,如果用户登录的用户名、密码符合要求,就可以访问被保护资源了。
       在Android应用程序中, 则可使用HttpClient 来登录系统,只要应用程序使用同一个HttpClient 发送请求,HttpClient 会自动维护与服务器之间的Session状态,也就是说程序第一次使用HttpClient 登录系统后,接下来使用HttpClient 即可访问被保护页而了。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值