首先:在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能:HttpURLConnection。但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。
在Android中,androidSDK中集成了Apache的HttpClient模块,用来提供高效的、最新的、功能丰富的支持 HTTP 协议工具包,并且它支持 HTTP 协议最新的版本和建议。使用HttpClient可以快速开发出功能强大的Http程序。

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

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

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对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

具体对比如下:HTTPClient

String url = "http://192.168.1.100:8080"; 
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"); 
  //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); 
    return response; 
}else{ 
    return "error"; 
  } 
} catch (ClientProtocolException e) { 
   e.printStackTrace(); 
   return "exception"; 
} catch (IOException e) { 
   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) { 
        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); 
     return response; 
  }else{ 
     return "error"; 
  } 
  } catch (ClientProtocolException e) { 
    e.printStackTrace(); 
    return "exception"; 
  } catch (IOException e) { 
    e.printStackTrace(); 
    return "exception"; 
   } 
}

HttpURLConnection:

String url = "http://192.168.1.100:8080"; 
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; 
 } 
}

客户端操作:

String url = "http://192.168.1.102:8080"; 
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) { 
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(); 
}

HTTPClient和URLConnection核心区别分析的更多相关文章

  1. C++中关于[]静态数组和new分配的动态数组的区别分析

    这篇文章主要介绍了C++中关于[]静态数组和new分配的动态数组的区别分析,很重要的概念,需要的朋友可以参考下 本文以实例分析了C++语言中关于[]静态数组和new分配的动态数组的区别,可以帮助大家加 ...

  2. Java中Comparable和Comparator接口区别分析

    Java中Comparable和Comparator接口区别分析 来源:码农网 | 时间:2015-03-16 10:25:20 | 阅读数:8902 [导读] 本文要来详细分析一下Java中Comp ...

  3. Oracle nvchar2和varchar2区别分析

    Oracle nvchar2和varchar2区别分析: [注意]VARCHAR2是Oracle提供的特定数据类型,Oracle可以保证VARCHAR2在任何版本中该数据类型都可以向上和向下兼容.VA ...

  4. jQuery中的.bind()、.live()和.delegate()之间区别分析

    jQuery中的.bind()..live()和.delegate()之间区别分析,学习jquery的朋友可以参考下.   DOM树   首先,可视化一个HMTL文档的DOM树是很有帮助的.一个简单的 ...

  5. jQuery中的bind() live() delegate()之间区别分析

    jQuery中的bind() live() delegate()之间区别分析 首先,你得要了解我们的事件冒泡(事件传播)的概念,我先看一张图 1.bind方式 $('a').bind('click', ...

  6. addEventListener()及attachEvent()区别分析

    Javascript 的addEventListener()及attachEvent()区别分析 Mozilla中: addEventListener的使用方式: target.addEventLis ...

  7. C# Parse和Convert的区别分析

    原文:C# Parse和Convert的区别分析 大家都知道在进行类型转换的时候有连个方法供我们使用就是Convert.to和*.Parse,但是疑问就是什么时候用C 什么时候用P 通俗的解释大家都知 ...

  8. Zepto源码分析(一)核心代码分析

    本文只分析核心的部分代码,并且在这部分代码有删减,但是不影响代码的正常运行. 目录 * 用闭包封装Zepto * 开始处理细节 * 正式处理数据(获取选择器选择的DOM) * 正式处理数据(添加DOM ...

  9. jquery中attr和prop的区别分析

    这篇文章主要介绍了jquery中attr和prop的区别分析的相关资料,需要的朋友可以参考下 在高版本的jquery引入prop方法后,什么时候该用prop?什么时候用attr?它们两个之间有什么区别 ...

随机推荐

  1. 转:MySql的commit和rollback

    从功能上划分,SQL 语言可以分为DDL,DML和DCL三大类.1. DDL(Data Definition Language)     数据定义语言,用于定义和管理 SQL 数据库中的所有对象的语言 ...

  2. CMake入门指南

    原文地址:http://www.cnblogs.com/sinojelly/archive/2010/05/22/1741337.html CMake是一个比make更高级的编译配置工具,它可以根据不 ...

  3. quant_百度百科

    quant_百度百科     quant    编辑    quant的工作就是设计并实现金融的数学模型(主要采用计算机编程),包括衍生物定价,风险估价或预测市场行为等.所以quant更多可看为工程师 ...

  4. Log4Net五步走

    本文不是教你全面了解log4net,本文只是希望教会你按步就班,照糊芦画瓢般就会用log4net1,引入log4net.dll组件2,建立一个配置文件两种方法,一种是在Web.Config或App.C ...

  5. 采用xml的方式保存数据

    package com.example.myxmlmake; import java.io.File; import java.io.FileOutputStream; import java.uti ...

  6. Android中的单元测试

    2015年5月19日 23:10     在Android中,已经内置了Junit所以不需要在导包.只要继承AndroidTestCase类就可以了.     首先需要修改AndroidManifes ...

  7. splinter python浏览器自动化操作,模拟浏览器的行为

    Splinter可以非常棒的模拟浏览器的行为,Splinter提供了丰富的API,可以获取页面的信息判断当前的行为所产生的结果   最近在研究网站自动登录的问题,涉及到需要实现浏览器自动化操作,网上有 ...

  8. php实现加好友功能

    思路: 1用户发送好友申请之后 把申请储存到申请数据表中,状态为 未验证 2 当用户登录时,查询申请表中是否有uid和被申请人id相同的,如果同意,更改状态,并把数据插入到对应的好友数据表否则,删除申 ...

  9. [置顶] think in java interview-高级开发人员面试宝典(八)

    面经出了7套,收到许多读者的Email,有许多人说了,这些基础知识是不是为了后面进一步的”通向架构师的道路“做准备的? 对的,你们没有猜错,就是这样的,我一直在酝酿后面的”通向架构师的道路“如何开章. ...

  10. tcp接收xml数据解析

    避免tcp接收xml数据时加上xml数据长度,根据xml数据特点来解析recv到的xml数据 int nPos1 = 0; int nPos2 = 0; int nTempPos = 0; int n ...