文档章节

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

Carbenson
 Carbenson
发布于 2015/09/25 11:46
字数 902
阅读 572
收藏 2

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.案例

HttpURLConnection

String urlAddress = "http://192.168.1.102:8080/AndroidServer/login.do";
URL url;
HttpURLConnection uRLConnection;
publicUrlConnectionToServer(){

}//向服务器发送get请求
publicString doGet(String username,String password){
String getUrl = urlAddress + "?username="+username+"&password="+password;
try{
url =newURL(getUrl);
uRLConnection = (HttpURLConnection)url.openConnection();
InputStream is = uRLConnection.getInputStream();
BufferedReader br =newBufferedReader(newInputStreamReader(is));
String response = "";
String readLine =null;
while((readLine =br.readLine()) !=null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
returnresponse;
}catch(MalformedURLException e) {
e.printStackTrace();
returnnull;
}catch(IOException e) {
e.printStackTrace();
returnnull;
}
}
 //向服务器发送post请求
publicString doPost(String username,String password){
try{
url =newURL(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 =newDataOutputStream(uRLConnection.getOutputStream());
String content = "username="+username+"&password="+password;
out.writeBytes(content);
out.flush();
out.close();

InputStream is = uRLConnection.getInputStream();
BufferedReader br =newBufferedReader(newInputStreamReader(is));
String response = "";
String readLine =null;
while((readLine =br.readLine()) !=null){
//response = br.readLine();
response = response + readLine;
}
is.close();
br.close();
uRLConnection.disconnect();
returnresponse;
}catch(MalformedURLException e) {
e.printStackTrace();
returnnull;
}catch(IOException e) {
e.printStackTrace();
returnnull;
}
}

HTTPClient

String urlAddress = "http://192.168.1.102:8080/qualityserver/login.do";
publicHttpClientServer(){

}

publicString doGet(String username,String password){
String getUrl = urlAddress + "?username="+username+"&password="+password;
HttpGet httpGet =newHttpGet(getUrl);
HttpParams hp = httpGet.getParams();
hp.getParameter("true");
//hp.
//httpGet.setp
HttpClient hc =newDefaultHttpClient();
try{
HttpResponse ht = hc.execute(httpGet);
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity he = ht.getEntity();
InputStream is = he.getContent();
BufferedReader br =newBufferedReader(newInputStreamReader(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);
returnresponse;
}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";
}
}

publicString doPost(String username,String password){
//String getUrl = urlAddress + "?username="+username+"&password="+password;
HttpPost httpPost =newHttpPost(urlAddress);
List params =newArrayList();
NameValuePair pair1 =newBasicNameValuePair("username", username);
NameValuePair pair2 =newBasicNameValuePair("password", password);
params.add(pair1);
params.add(pair2);

HttpEntity he;
try{
he =newUrlEncodedFormEntity(params, "gbk");
httpPost.setEntity(he);

}catch(UnsupportedEncodingException e1) {
//TODO Auto-generated catch block
e1.printStackTrace();
}

HttpClient hc =newDefaultHttpClient();
try{
HttpResponse ht = hc.execute(httpPost);
//连接成功
if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity het = ht.getEntity();
InputStream is = het.getContent();
BufferedReader br =newBufferedReader(newInputStreamReader(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);
returnresponse;
}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 =newToDo();
List<UserBean> list =newArrayList<UserBean>();
list = toDo.queryUsers(mySession);
String body;

//设定JSON
JSONArray array =newJSONArray();
for(UserBean bean : list)
{
JSONObject obj =newJSONObject();
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 =newJSONArray(body);
for(inti=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 =newHashMap<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 =newSimpleAdapter(this,listItem,
android.R.layout.simple_list_item_2,
newString[]{"username","password"},
newint[]{android.R.id.text1,android.R.id.text2});
listResult.setAdapter(simple);

listResult.setOnItemClickListener(newOnItemClickListener() {
@Override
publicvoidonItemClick(AdapterView<?> parent, View view,
intposition,longid) {
intpositionId = (int) (id+1);
Toast.makeText(MainActivity.this, "ID:"+positionId, Toast.LENGTH_LONG).show();

}
});
}
privatevoidextracted() {
showResult.setText("没有有效的数据!");
}
//和服务器连接
privateString getContent(String url)throwsException{
StringBuilder sb =newStringBuilder();
HttpClient client =newDefaultHttpClient();
HttpParams httpParams =client.getParams();

HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpResponse response = client.execute(newHttpGet(url));
HttpEntity entity =response.getEntity();

if(entity !=null){
BufferedReader reader =newBufferedReader(newInputStreamReader
(entity.getContent(),"UTF-8"),8192);
String line =null;
while((line= reader.readLine())!=null){
sb.append(line +"\n");
}
reader.close();
}
returnsb.toString();
}


本文转载自:http://xiaowei-qi-epro-com-cn.iteye.com/blog/1973295

Carbenson
粉丝 19
博文 271
码字总数 84864
作品 0
广州
程序员
私信 提问
Android下的网络编程 & 代理的使用

1. 使用 标准Java接口: 设计的类: java.net.* 基本步骤: 1) 创建 URL 以及 URLConnection / HttpURLConnection 对象 2) 设置连接参数 3) 连接到服务器 4) 向服务器写数据 5)从服务器读取数据...

小编辑
2010/08/12
5.5K
2
Java HTTP 组件库选型看这篇就够了

原文出处:行思錄 Java HTTP 组件库选型看这篇就够了 最近项目需要使用 Java 重度调用 HTTP API 接口,于是想着封装一个团队公用的 HTTP client lib. 这个库需要支持以下特性: 连接池管理,...

行思錄
2018/09/25
0
0
HttpClient和HttpURLConnection的区别

Android 提供两个HTTP客户端,分别是HttpURLConnection客户端和Apache的HttpClient,android的AndroidHttpClient是对HttpClient的实现。这两个HTTP客户端都支持HTTPS协议、流媒体的上传和下载...

Callen
2015/08/09
1K
0
android中网络操作使用总结(http)

Android是作为智能手机的操作系统,我们开发的应用,大多数也都需要连接网络,通过网络发送数据、获取数据,因此作为一个应用开发者必须熟悉怎么进行网络访问与连接。通常android中进行网络连...

码农明明
2014/05/22
3K
6
HTTP协议和HttpClient的入门

HTTP协议的发展史没有了解,是给予请求与响应模式的、无连接、无状态的应用层的协议。 HTTP协议 HTTP协议的URL HTTP URL(URL是一种特殊类型的URI,包含了勇于查找某个资源的足够的信息)的格式...

凹凸口天
2013/07/15
3.9K
0

没有更多内容

加载失败,请刷新页面

加载更多

浅谈prototype原型模式

一、原型模式简介 原型(Prototype)模式是一种对象创建型模式,他采取复制原型对象的方法来创建对象的实例。使用原型模式创建的实例,具有与原型一样的数据。 原型模式的特点: 1、由原型对...

青衣霓裳
13分钟前
2
0
shell mysql 备份

#!/bin/bash time2=$(date "+%Y-%m-%d-%H:%M:%S") /usr/local/mysql/bin/mysqldump -uroot -p ad > /usr/local/mysql/backup/"$time2".sql 变量引用原来是这么用的。......

奋斗的小牛
21分钟前
3
0
Jmeter监控Linux服务器操作

系统:Win7 64位 工具:Jmeter 4.0 要准备好的插件:JMeterPlugins-Standard-1.4.0,ServerAgent-2.2.1 解压JMeterPlugins-Standard-1.4.0.zip,将其中\lib\ext\JMeterPlugins-Standard.jar......

魔鬼妹子
21分钟前
4
0
系列文章:云原生Kubernetes日志落地方案

在Logging这块做了几年,最近1年来越来越多的同学来咨询如何为Kubernetes构建一个日志系统或者是来求助在这过程中遇到一系列问题如何解决,授人以鱼不如授人以渔,于是想把我们这些年积累的经...

Mr_zebra
22分钟前
3
0
入门必备!快速学会用Aspose.Words在表格中插入和删除列!

Aspose.Words For .Net(点击下载)是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft W...

mnrssj
27分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部