`
haliluya4
  • 浏览: 123397 次
  • 性别: Icon_minigender_1
  • 来自: 福州
社区版块
存档分类
最新评论

[转]URLConnection和HTTPClient的比较

 
阅读更多

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

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 = nullwhile((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 = nullwhile((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 = nullwhile((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;  }elsereturn "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 = nullwhile((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;  }elsereturn "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 =nullwhile ((line= reader.readLine())!=null){  sb.append(line +"\n");  }  reader.close();  }  return sb.toString();  }
 

URLConnection

HTTPClient

Proxies and SOCKS

Authorization

Methods

Headers

Automatic Redirection Handling

Persistent Connections

Pipelining of Requests

Can handle protocols other than HTTP

Can do HTTP over SSL (https)

Source code available

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.

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.

Only has GET and POST.

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

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.

Yes.

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

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.

No.

Yes.

Theoretically; however only http is currently implemented.

No.

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

No (not yet).

No.

Yes.

分享到:
评论

相关推荐

    HttpURLConnection和HTTPClient的比较,以及使用规则

    NULL 博文链接:https://xiaowei-qi-epro-com-cn.iteye.com/blog/1973295

    httpClient和URLConnection的区别

    在Android应用开发中,进行网络通信是常见的任务,其中两种主要的请求方式是使用`HttpURLConnection`和`HttpClient`。虽然两者都能实现HTTP通信,但它们在功能、使用方式和性能上存在一些区别。 首先,Apache ...

    java.net.URLConnection发送HTTP请求与通过Apache HttpClient发送HTTP请求比较

    总结来说,`java.net.URLConnection`适合简单、轻量级的HTTP请求,而Apache HttpClient更适合需要处理复杂HTTP逻辑和高性能需求的场景。开发人员应根据项目需求和自身技术水平来选择合适的方法。对于初学者,可以先...

    Web Service Tester

    【描述】Web Service Tester是一个针对Android 2.0平台的Eclipse工程,它演示了如何使用URLConnection和HttpClient两种方法来执行对WebService的GET和POST请求。这个工具对于开发者来说,是理解和实践网络通信的重要...

    HttpClient-4.5所需jar包.rar

    HttpClient 4.5版本是该库的一个稳定版本,相较于JDK自带的URLConnection,HttpClient提供了更多的优势和特性,特别适合于复杂的网络应用和爬虫开发。 1. **易用性**:HttpClient提供了丰富的API接口,使得创建HTTP...

    Android使用HttpClient和HttpsUrlConnection两种方式访问https网站

    本文将详细介绍如何使用`HttpClient`和`HttpsURLConnection`两种方式来访问HTTPS网站,包括验证证书和不验证证书的实现方法。 ### 1. Android中的HttpClient `HttpClient`是Apache提供的一种HTTP客户端库,它支持...

    HTTPClient组件的应用

    它弥补了JDK内置的java.net包中URL和URLConnection类在HTTP客户端编程方面的不足,提供了更丰富和灵活的功能。HttpClient组件允许应用程序直接通过HTTP协议访问Web服务器上的资源,这对于RIA(Rich Internet ...

    HttpClient入门陆小马功钟浩.pdf

    JDK提供了***.*包下的多个类来处理网络通信,如URL和URLConnection等。使用URL类的实例可以打开一个网络资源的输入流,获取网页内容是网络编程中最基础的操作之一。通过建立URL对象,并调用openStream方法,可以直接...

    httpclientUtil

    1.基于HttpClient-4.4.1封装的一个工具类; 2.基于HttpAsycClient-4.1封装的异步HttpClient工具类; 3.javanet包下面是基于jdk自带的UrlConnection进行封装的。 前2个工具类支持插件式配置Header、插件式配置...

    URL以及URLConnection的使用

    在Java编程语言中,URL(Uniform Resource Locator)和URLConnection是两个关键的概念,它们在处理网络资源的访问和交互中起到核心作用。本文将深入探讨URL的构造与解析、URLConnection的功能和使用方法,以及如何...

    客户端页面截取!URLCONNECTION

    在IT行业中,客户端页面截取是一项常见的需求...虽然HttpClient在许多场景下更受欢迎,但了解和掌握URLCONNECTION的使用也能增强我们解决网络通信问题的能力。在实际开发中,选择哪种方式取决于具体的需求和项目规模。

    ApacheCommons-HTTPClient组件的应用.doc

    由于JDK内置的java.net.URL和URLConnection类在功能上可能不足以满足复杂的需求,Commons-HTTPClient 提供了更为丰富和灵活的功能。 HttpClient 支持HTTP 1.0和1.1协议的全部方法,包括GET、POST、PUT、DELETE、...

    java URL URLConnection

    在Java编程语言中,`URL`(统一资源定位符)和`URLConnection`是网络编程中的核心类,用于访问和交互互联网上的资源。这篇博客文章可能深入解析了这两个类的使用和内部工作原理。 `URL`类是Java.net包中的一个关键...

    httpclient 绕开HTTPS证书校验

    在`httpclient-4.2.5.jar`这个版本中,我们可以找到实现这一功能的相关类和方法。`httpcore-4.2.4.jar`则是`httpclient`的基础库,提供了HTTP协议的核心组件,如连接管理、请求和响应模型等。 为了绕过HTTPS证书...

    Android例子源码使用HttpClient获取网页html源代码

    本例子源码展示了如何利用Apache HttpClient库来实现这一功能,同时也对比了另一种常见的网络访问方式——URLConnection。以下是对这两个方法的详细解释。 首先,我们来看`HttpClient`的使用。Apache HttpClient是...

    JAVA调用HTTP及httpclient的详细说明

    // 打开连接,URL.openConnection函数会根据URL的类型,返回不同的URLConnection子类的对象 HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); // 进行连接 connection.connect();...

    详解Java两种方式简单实现:爬取网页并且保存

    这两种方法都可以实现网页的爬取和保存,`URLConnection`适用于简单的爬取需求,而`HttpClient`则提供了更多功能和更好的灵活性,适合处理复杂的情况。选择哪种方法取决于具体项目的需求和性能考虑。在实际开发中,...

Global site tag (gtag.js) - Google Analytics