Httpclient学习总结
网上很多HttpClient的学习源码都是3版本的,不过,既然现在HttpClient已经升级成Apache的顶级项目,自然想使用新版本。但是4版本完全是重新编写,而不能向下兼容。所以在学习调试源码时,利用的4的库,就不能直接运行3.1下的源码。
首先要区分是httpClient的jar包,长得很像,很容易混淆;jar包的变更,把org.apache.commons.httpclient.*修改到import org.apache.http.*。具体变更哪些,就要看利用了HttpClient的哪些功能:
HttpClient3版本
Java代码
1. import org.apache.commons.httpclient.HttpClient;
2. import org.apache.commons.httpclient.HttpStatus;
3. import org.apache.commons.httpclient.HttpException;
4. import org.apache.commons.httpclient.methods.GetMethod;
5. import org.apache.commons.httpclient.ConnectTimeoutException;
HttpClient4版本
Java代码
1. import org.apache.http.client.HttpClient;
2. import org.apache.http.HttpStatus;
3. import org.apache.http.HttpException;
4. import org.apache.http.client.methods.HttpGet;
5. import org.apache.http.conn.ConnectTimeoutException;
6. import org.apache.http.HttpResponse;
7. import org.apache.http.impl.client.DefaultHttpClient;
1.首先我们需要一个HttpClient的实例:
CloseableHttpClient httpclient = HttpClients.createDefault();//创建一个httpclient
2.然后我们需要Http的请求方法,有HttpGet,HttpPost,HttpPut,HttpDelete,等等,我们集中在这讨论HttpGet,HttpPost两个方法。先来个HttpGet的流程吧。
新建HttpGet实例:
3.HttpGet是可以带头参数的,有两种方法,第一种是用HttpClient程序包为我们提供了URIUtils工具类,可以通过它生成带参数的URI,如:
URI uri = URIUtils.createURI("http", "localhost", -1, "/index.html",
"param1=value1¶m2=value2", null);
HttpUriRequest request = new HttpGet(uri);
第二种是自己写一个可以传入hashMap的参数,然后自己拼接参数。我用的是第二种,
方法如下:需要注意的是如果含有中文需要转码,URLEncoder.encode("中国", "UTF-8")
**
*
* @param url 请求地址
* @param paras 加入地址请求的参数
* @return 返回拼接好的请求地址
*/
public static String joinParam(String url, Map<String, Object> paras){
if(paras!=null){
Iterator<Map.Entry<String,Object>> iter=paras.entrySet().iterator();
url=url+'?';
Map.Entry<String , Object > entry = iter.next();
url=url+entry.getKey()+'='+entry.getValue();
while(iter.hasNext()&&(paras!=null)){
Map.Entry<String , Object > entry1 = iter.next();
url=url+'&'+entry1.getKey()+'='+entry1.getValue();
}
}
return url;
}
4.HttpPost的加入参数方法,类如下。
/**
*
* @param post post请求
* @param paras post请求带的参数
* 把参数加入Post头部
*/
public static void add_Entity(HttpPost post, Map<String,String> paras){
if(paras!=null){
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = paras.keySet();
for(String key : keySet) {
nvps.add(new BasicNameValuePair(key, paras.get(key)));
}
try {
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
5.执行请求:
HttpResponse response = httpClient.execute(request);
6 获取响应实体:
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity,"UTF-8");
}
具体参考代码如下:
HttpGet httpget=new HttpGet(); //创建一个httpget
3./**
* the method httpget.
* 有四个参数
* url 请求地址
* params 请求带的参数
* header 请求的头部
* soTimeout 请求连接时间
*/
public static String get(String url, Map<String, Object> params,Map<String, String> header, int soTimeout) {
CloseableHttpClient httpclient = HttpClients.createDefault();//创建一个httpclient
HttpGet httpget=new HttpGet(); //创建一个httpget
String result = null;
//拼接url
url=joinParam(url,params);
try {
if (url != null) {
httpget.setURI(URI.create(url));
}
//add header
add_Header(httpget,header);
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
*setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
*setSocketTimeout:请求获取数据的超时时间,单位毫秒。
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(soTimeout).setConnectionRequestTimeout(soTimeout)
.setSocketTimeout(soTimeout).build();
httpget.setConfig(requestConfig);
// 执行get请求.
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpget);
} catch (IOException e) {
e.printStackTrace();
}
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity,"UTF-8");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* the method httpPost.
* 有五个参数
* url 请求地址
* body 请求头带的参数
* entity 请求体带的参数
* header 请求的头部
* soTimeout 请求连接时间
*/
public static String post(String url, Map<String, Object> body,Map<String, Object> entity,Map<String, String> header, int soTimeout) {
CloseableHttpClient httpclient = HttpClients.createDefault();//创建一个httpclient
HttpPost httppost= new HttpPost(); //创建一个httppost
String result = null;
try {
//拼接url
url=joinParam(url,body);
//add request url
if (url != null) {
httppost.setURI(URI.create(url));
}
//add header
add_Header(httppost,header);
if(entity!=null) {
String json = JSONObject.toJSONString(entity);
httppost.setEntity(new StringEntity(json, "UTF-8"));
}
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
*setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
*setSocketTimeout:请求获取数据的超时时间,单位毫秒。
*/
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(soTimeout).setConnectionRequestTimeout(soTimeout)
.setSocketTimeout(soTimeout).build();
httppost.setConfig(requestConfig);
//add entity
// add_Entity(httppost,entity);
// 执行post请求.
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
try {
// 获取响post应实体
HttpEntity postentity = response.getEntity();
if (postentity != null) {
result = EntityUtils.toString(postentity,"UTF-8");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
*
* @param get 请求
* @param paras get请求带的头部信息
* 功能是把头部信息加入get中
*/
public static void add_Header(HttpRequestBase get, Map<String,String> paras){
if(paras!=null){
Iterator<Map.Entry<String,String>> iter=paras.entrySet().iterator();
while(iter.hasNext()&&(paras!=null)){
Map.Entry<String , String > entry = iter.next();
get.addHeader(entry.getKey(),entry.getValue());
}
}
}
/**
*
* @param url 请求地址
* @param paras 加入地址请求的参数
* @return 返回拼接好的请求地址
*/
public static String joinParam(String url, Map<String, Object> paras){
if(paras!=null){
Iterator<Map.Entry<String,Object>> iter=paras.entrySet().iterator();
url=url+'?';
Map.Entry<String , Object > entry = iter.next();
url=url+entry.getKey()+'='+entry.getValue();
while(iter.hasNext()&&(paras!=null)){
Map.Entry<String , Object > entry1 = iter.next();
url=url+'&'+entry1.getKey()+'='+entry1.getValue();
}
}
return url;
}