public class HttpClientUtil {
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";
private HttpClient httpclient;
/**
* 通過post提交方式獲取url指定的資源和數據
*
* @param url
* @return
* @throws Exception
*/
public String postData(String url) throws Exception {
return postData(url, null);
}
/**
* 通過post提交方式獲取url指定的資源和數據
*
* @param url
* @param nameValuePairs
* 請求參數
* @return
* @throws Exception
*/
public String postData(String url, List<NameValuePair> nameValuePairs)
throws Exception {
return postData(url, nameValuePairs, null);
}
/**
* 通過post提交方式獲取url指定的資源和數據
*
* @param url
* @param nameValuePairs
* 請求參數
* @param headers
* 請求header參數
* @return
* @throws Exception
*/
public String postData(String url,
List<NameValuePair> nameValuePairs, Map<String, String> headers)
throws Exception {
long start = System.currentTimeMillis();
HttpPost httpPost = new HttpPost(url);
try {
if (headers != null && headers.size() > 0) {
Set<Map.Entry<String, String>> set = headers.entrySet();
for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
.hasNext();) {
Map.Entry<String, String> header = it.next();
if (header != null) {
httpPost.setHeader(header.getKey(), header.getValue());
}
}
}
if (nameValuePairs != null && nameValuePairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
}
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity == null){
return null;
}
String info = EntityUtils.toString(entity, "UTF-8");
return info;
} catch (Exception e) {
throw new Exception(url
+ " postData exception:", e);
} finally {
httpPost.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
/**
* 通過ContentType 爲json的格式進行http傳輸
* @param url 遠程url
* @param content 傳輸內容
* @return
* @throws Exception
*/
public String postJSONData(String url, String content) throws Exception {
long start = System.currentTimeMillis();
HttpPost httpPost = new HttpPost(url);
//httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
try {
if (content != null && content.length() > 0) {
StringEntity se = new StringEntity(content,ContentType.APPLICATION_JSON);
//se.setContentEncoding("UTF-8");
httpPost.setEntity(se);
}
HttpResponse response = httpclient.execute(httpPost);
//response.addHeader("Content-Type", "application/json; charset=utf-8");
HttpEntity entity = response.getEntity();
if(entity == null){
return null;
}
String info = EntityUtils.toString(entity, "utf-8");
return info;
} catch (Exception e) {
throw new Exception(url
+ " postDataByJson exception:", e);
} finally {
httpPost.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
/**
* 通過get方法獲取url資源的數據
*
* @param url
* 服務器地址
* @return 返回響應的文本,如果請求發生異常,拋出Exception
* @throws Exception
*/
public String getData(String url) throws Exception {
return getData(url, null);
}
/**
* 帶header的get請求
*
* @param url
* 服務器地址
* @param headers
* 添加的請求header信息
* @return 返回服務器響應的文本,出錯拋出Exception異常
* @throws Exception
*/
public String getData(String url, Map<String, String> headers)
throws Exception {
long start = System.currentTimeMillis();
HttpGet httpGet = new HttpGet(url);
if (headers != null && headers.size() > 0) {
Set<Map.Entry<String, String>> set = headers.entrySet();
for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
.hasNext();) {
Map.Entry<String, String> header = it.next();
if (header != null) {
httpGet.setHeader(header.getKey(), header.getValue());
}
}
}
try {
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity == null){
return null;
}
String info = EntityUtils.toString(entity, "UTF-8");
return info;
} catch (Exception e) {
throw new Exception(url
+ " getData exception:", e);
} finally {
httpGet.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
/**
* call webservice
* @param url
* @param content
* @param soapAction
* @return
* @throws Exception
*/
public String postWebService(String url, String content,String soapAction) throws Exception {
String result = "";
HttpPost httppost = new HttpPost(url);
try {
HttpEntity re = new StringEntity(content,HTTP.UTF_8);
httppost.setHeader("Content-Type","text/xml; charset=UTF-8");
httppost.setHeader("SOAPAction", soapAction);
// httppost.setHeader("Content-Type","application/soap+xml; charset=utf-8");
// httppost.setHeader("Content-Length", String.valueOf(soapRequestData.length()));
httppost.setEntity(re);
HttpResponse response = httpclient.execute(httppost);
// System.out.println(EntityUtils.toString(httppost.getEntity()));
// System.out.println(response.getStatusLine());
result=EntityUtils.toString(response.getEntity());
// System.out.println(soapRequestData);
return result;
} catch (Exception e) {
throw new Exception(url + "postWebService exception:", e);
}finally{
httppost.releaseConnection();
}
}
/**
* 對httpclient 做壓縮處理和解壓縮處理
*
* @param httpclient
*/
public void initClient() {
HttpParams hps = new BasicHttpParams();
hps.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120*1000);//120 seconds
hps.setParameter(CoreConnectionPNames.SO_TIMEOUT, 120*1000);//120 seconds
((DefaultHttpClient)httpclient).setParams(hps);
((DefaultHttpClient)httpclient).addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) {
if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
}
});
((DefaultHttpClient)httpclient).addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context) {
final HttpEntity entity = response.getEntity();
if(entity == null){
return;
}
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
response.setEntity(new GzipDecompressingEntity(
response.getEntity()));
break;
}
}
}
}
});
}
/**
* 關閉客戶端
*/
public void destroyClient(){
httpclient.getConnectionManager().shutdown();
}
/**
* post方式處理文件和圖片上傳
*
* @param url
* 服務器地址
* @param data
* byte數組數據
* @param fileName
* 文件名
* @return 返回服務器響應信息,否則拋出Exception異常
* @throws Exception
*/
public String postMultipartData(String url, byte[] data,
String fileName) throws Exception {
long start = System.currentTimeMillis();
HttpPost httpPost = new HttpPost(url);
try {
if (data != null && data.length > 0) {
MultipartEntity reqEntity = new MultipartEntity();
ContentBody contentBody = new ByteArrayBody(data, fileName);
reqEntity.addPart("file", contentBody);
httpPost.setEntity(reqEntity);
}
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
String info = EntityUtils.toString(entity, "UTF-8");
return info;
} catch (Exception e) {
throw new Exception(url
+ " postMultipartData exception:", e);
} finally {
httpPost.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
/**
* form and data
* @param url
* @param data
* @param fileName
* @return
* @throws Exception
*/
public String postMultipartData(String url, byte[] data,
String fileName,List<NameValuePair> nameValuePairs) throws Exception {
long start = System.currentTimeMillis();
HttpPost httpPost = new HttpPost(url);
try {
if (data != null && data.length > 0) {
MultipartEntity reqEntity = new MultipartEntity();
ContentBody contentBody = new ByteArrayBody(data, fileName);
reqEntity.addPart("file", contentBody);
httpPost.setEntity(reqEntity);
if (nameValuePairs != null && nameValuePairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
}
}
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
String info = EntityUtils.toString(entity, "UTF-8");
return info;
} catch (Exception e) {
throw new Exception(url
+ " postMultipartData exception:", e);
} finally {
httpPost.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
/**
* put 方式提交數據
*
* @param url
* :服務器地址
* @param nameValuePairs
* :參數
* @return 返回 服務器返回的文本信息,報錯會拋出異常
* @throws Exception
*/
public String putData(String url, List<NameValuePair> nameValuePairs)
throws Exception {
long start = System.currentTimeMillis();
HttpPut httpPut = new HttpPut(url);
try {
if (nameValuePairs != null && nameValuePairs.size() > 0) {
httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
}
HttpResponse response = httpclient.execute(httpPut);
HttpEntity entity = response.getEntity();
if(entity == null){
return null;
}
String info = EntityUtils.toString(entity, "UTF-8");
return info;
} catch (Exception e) {
throw new Exception(url
+ " putData exception:", e);
} finally {
httpPut.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
/**
* delete 方式提交數據
*
* @param url
* 服務器地址
* @return 返回 服務器返回的文本信息,報錯會拋出異常
* @throws Exception
*/
public String deleteData(String url)
throws Exception {
return deleteData(url, null);
}
/**
* delete 方式提交數據
*
* @param url
* 服務器地址
* @return 返回 服務器返回的文本信息,報錯會拋出異常
*/
public String deleteData(String url, Map<String, String> headers)
throws Exception {
long start = System.currentTimeMillis();
HttpDelete httpDelete = new HttpDelete(url);
if (headers != null && headers.size() > 0) {
Set<Map.Entry<String, String>> set = headers.entrySet();
for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
.hasNext();) {
Map.Entry<String, String> header = it.next();
if (header != null) {
httpDelete.setHeader(header.getKey(), header.getValue());
}
}
}
try {
HttpResponse response = httpclient.execute(httpDelete);
HttpEntity entity = response.getEntity();
String info = EntityUtils.toString(entity, "UTF-8");
return info;
} catch (Exception e) {
throw new Exception(url
+ " deleteDate exception:", e);
} finally {
httpDelete.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
/**
* 下載媒體資源
* @param url
* @return
* @throws Exception
*/
public byte[] getMultipartData(String url) throws Exception{
long start = System.currentTimeMillis();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpclient.execute(httpGet);
byte[] result = EntityUtils.toByteArray(response.getEntity());
return result;
}catch(Exception e){
throw new Exception(url+ " getMultipartData exception:", e);
}finally{
httpGet.releaseConnection();
long interval = System.currentTimeMillis() - start;
}
}
public void setHttpclient(HttpClient httpclient) {
this.httpclient = httpclient;
}
}`這裏寫代碼片`
HttpClientUtil(交互三方接口)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.