[文章作者:卢键 本文版本:v2.0 最后修改:2011.02.22 转载请注明原文链接:http://blog.lujian.org/httpclient4_v2]
添加了gzip压缩数据的处理
对基本的get,post及获取文件及post字符串进行了封装
httpclient4 lib包请到http://hc.apache.org/下载
或配置maven自动获取:
引用
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.0</version>
</dependency>
package org.lujian.base.http;
/**
* @author lujian
*/
public interface WebHeaderConstant {
//
public final static String WEB_ACCEPT_XML = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
public final static String WEB_ACCEPT_JSON = "application/json, text/javascript, */*";
public final static String WEB_ACCEPT_CHARSET = "GBK,utf-8;q=0.7,*;q=0.3";
public final static String WEB_ACCEPT_ENCODING = "gzip,deflate,sdch";
public final static String WEB_ACCEPT_LANGUAGE = "zh-CN,zh;q=0.8";
public final static String WEB_CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8";
public final static String WEB_USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.84 Safari/534.13 By LuJian's Client";
public final static String WEB_X_REQUESTED_WITH = "XMLHttpRequest";
}
package org.lujian.base.http;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.params.*;
import org.apache.http.conn.params.*;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.client.*;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.*;
/**
* http访问 封装
* @author lujian
*/
public class HttpWebClient {
private String charset = "GBK";
private HttpClient httpclient;
/**
* 构造方法
*/
public HttpWebClient() {
httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
}
/**
* 构造方法
* @param charset
*/
public HttpWebClient(String charset) {
this();
this.charset = charset;
}
/**
* 构造方法 :使用代理连接
* @param ip
* @param port
*/
public HttpWebClient(String ip, int port) {
this();
HttpHost proxy = new HttpHost(ip, port);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
private HttpGet setHttpGetHeader(HttpGet httpGet, Map<String, Object> headers) {
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue().toString());
}
}
return httpGet;
}
public String get(HttpGet httpget) throws IOException {
HttpResponse response = httpclient.execute(httpget);
return this.getResponseBodyAsString(response);
}
public String get(Map<String, Object> headers, String url) throws IOException {
HttpGet httpget = new HttpGet(url);
httpget = this.setHttpGetHeader(httpget, headers);
return this.get(httpget);
}
private String get(String url, String headerAccept) throws IOException {
Map<String, Object> headers = this.getCommonHeader();
headers.put("Accept", headerAccept);
return this.get(headers, url);
}
public String get(String url) throws IOException {
return this.get(url, WebHeaderConstant.WEB_ACCEPT_XML);
}
public String getJson(String url) throws IOException {
return this.get(url, WebHeaderConstant.WEB_ACCEPT_JSON);
}
public byte[] getFile(HttpGet httpget) throws IOException {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
byte[] bs = EntityUtils.toByteArray(entity);
if (entity != null) {
entity.consumeContent();
}
return bs;
}
public byte[] getFile(Map<String, Object> headers, String url) throws IOException {
HttpGet httpget = new HttpGet(url);
httpget = this.setHttpGetHeader(httpget, headers);
return this.getFile(httpget);
}
public byte[] getFile(String url) throws IOException {
Map<String, Object> headers = this.getCommonHeader();
headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
return this.getFile(headers, url);
}
public byte[] getFile(String url, File file) throws IOException {
byte[] bs = this.getFile(url);
FileOutputStream output = new FileOutputStream(file);
output.write(bs);
output.close();
return bs;
}
private HttpPost setHttpPostHeaderAndParams(HttpPost httpPost, Map<String, Object> headers, Map<String, Object> params) throws UnsupportedEncodingException {
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue().toString());
}
}
//
List nvps = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
nvps.add(new NameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
return httpPost;
}
public String post(HttpPost httppost) throws IOException {
HttpResponse response = httpclient.execute(httppost);
return this.getResponseBodyAsString(response);
}
public String post(Map<String, Object> headers, String url, Map<String, Object> params) throws IOException {
HttpPost httpPost = new HttpPost(url);
this.setHttpPostHeaderAndParams(httpPost, headers, params);
return this.post(httpPost);
}
public String post(String url, Map<String, Object> params) throws IOException {
Map<String, Object> headers = this.getCommonHeader();
headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
return this.post(headers, url, params);
}
public String postJson(String url, Map<String, Object> params) throws IOException {
Map<String, Object> headers = this.getCommonHeader();
headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_JSON);
return this.post(headers, url, params);
}
public String post(HttpPost httppost, String str) throws IOException {
StringEntity reqEntity = new StringEntity(str);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
return this.getResponseBodyAsString(response);
}
public String post(Map<String, Object> headers, String url, String str) throws IOException {
HttpPost httpPost = new HttpPost(url);
this.setHttpPostHeaderAndParams(httpPost, headers, null);
return this.post(httpPost, str);
}
public String post(String url, String str) throws IOException {
Map<String, Object> headers = this.getCommonHeader();
headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
return this.post(headers, url, str);
}
public String postJson(String url, String str) throws IOException {
Map<String, Object> headers = this.getCommonHeader();
headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_JSON);
return this.post(headers, url, str);
}
public String uploadFile(HttpPost httppost, File file) throws IOException {
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileBody);
// 设置请求
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
return this.getResponseBodyAsString(response);
}
public void close() {
httpclient.getConnectionManager().shutdown();
}
// ///
public HttpClient getHttpclient() {
return httpclient;
}
public void setCharset(String charset) {
this.charset = charset;
}
private String getResponseBodyAsString(HttpResponse response) throws IOException {
String html = null;
GZIPInputStream gzin;
if (response.getEntity().getContentEncoding() != null && response.getEntity().getContentEncoding().getValue().toLowerCase().indexOf("gzip") > -1) {
InputStream is = response.getEntity().getContent();
gzin = new GZIPInputStream(is);
InputStreamReader isr = new InputStreamReader(gzin, "iso-8859-1");
java.io.BufferedReader br = new java.io.BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String tempbf;
while (( tempbf = br.readLine() ) != null) {
sb.append(tempbf);
sb.append("\r\n");
}
isr.close();
gzin.close();
html = sb.toString();
html = new String(html.getBytes("iso-8859-1"), this.charset);
} else {
HttpEntity entity = response.getEntity();
html = EntityUtils.toString(entity, this.charset);
if (entity != null) {
entity.consumeContent();
}
}
return html;
}
private Map<String, Object> getCommonHeader() {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("Accept-Charset", WebHeaderConstant.WEB_ACCEPT_CHARSET);
headers.put("Accept-Encoding", WebHeaderConstant.WEB_ACCEPT_ENCODING);
headers.put("Accept-Language", WebHeaderConstant.WEB_ACCEPT_LANGUAGE);
headers.put("User-Agent", WebHeaderConstant.WEB_USER_AGENT);
return headers;
}
}
httpclient4的封装
最新推荐文章于 2024-03-22 21:17:22 发布