httpclient4.5工具類
package org.xxz.util;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
private static final Log log = LogFactory.getLog(HttpClientUtil.class);
/**
* 所需要的jar <br>
* httpclient-4.5.jar <br>
* httpcore-4.4.1.jar <br>
* httpmime-4.5.jar <br>
* commons-logging-1.2.jar <br>
*/
private RequestConfig config = RequestConfig.custom()//
.setSocketTimeout(5000)//
.setConnectTimeout(5000)//
.setConnectionRequestTimeout(5000)//
.build();
private Map<String, String> headers;
public HttpClientUtil setHeaders(Map<String, String> headers) {
this.headers = headers;
return this;
}
/**
* 單例模式
*/
private HttpClientUtil() {
}
public static final HttpClientUtil getInstance() {
return HttpClientUtilHolder.instance;
}
private static class HttpClientUtilHolder {
private static final HttpClientUtil instance = new HttpClientUtil();
}
/**
* get request
*
* @param url
* @param params
* @return
*/
public String get(String url, Map<String, String> params) {
StringBuffer buf = new StringBuffer();
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
buf.append(entry.getKey());
buf.append("=");
buf.append(entry.getValue());
buf.append("&");
}
}
url += buf.toString();
HttpGet httpGet = new HttpGet(url);
// 添加請求頭
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
// 設定請求逾時時間
httpGet.setConfig(config);
return req(httpGet);
}
/**
* post request
*
* @param url
* 請求位址
* @param params
* 普通參數
* @return
*/
public String post(String url, Map<String, String> params) {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(config);
// 設定請求頭
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("無效的字元編碼", e);
}
}
return req(httpPost);
}
/**
* post request entity
*
* @param url
* @param params
* @param file
* @return
*/
public String post(String url, Map<String, String> params, String fileKey, String file) {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(config);
// 設定請求頭
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
if (params != null && params.size() > 0) {
for (Map.Entry<String, String> entry : params.entrySet()) {
mBuilder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.TEXT_PLAIN));
}
}
// 添加檔案
mBuilder.addPart(fileKey, new FileBody(new File(file)));
httpPost.setEntity(mBuilder.build());
return req(httpPost);
}
/**
* 上傳檔案
*
* @param url
* @param fileKey
* @param file
* @return
*/
public String post(String url, String fileKey, String file) {
return post(url, null, fileKey, file);
}
/**
* 多檔案上傳
*
* @param url
* @param files
* 如果上傳的key一樣,建議使用IdentityHashMap <br>
* key使用new String()保證每一個對象不相等,不然隻會傳一次
* @return
*/
public List<String> postMultiFile(String url, Map<String, String> files) {
List<String> list = new ArrayList<String>();
if (files != null && files.size() > 0) {
for (Map.Entry<String, String> entry : files.entrySet()) {
list.add(post(url, entry.getKey(), entry.getValue()));
}
}
return list;
}
/**
* 發送請求
*
* @param request
* 請求方式
* @return
*/
private String req(HttpUriRequest request) {
String responseBody = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
responseBody = httpClient.execute(request, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
int statusCode = response.getStatusLine().getStatusCode();
log.info("----> statusCode: " + statusCode);
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
});
} catch (Exception e) {
throw new RuntimeException("httpclient execute error", e);
}
return responseBody;
}
public static void main(String[] args) throws Exception {
String url = "http://127.0.0.1:8080/uploader.json";
Map<String, String> files = new IdentityHashMap<String, String>() {
{
put(new String("file"), "e:/z/other/t.jpg");
put(new String("file"), "e:/z/other/t.jpg");
put(new String("file"), "e:/z/other/t.jpg");
put(new String("file"), "e:/z/other/t.jpg");
put(new String("file"), "e:/z/other/t.jpg");
}
};
HttpClientUtil.getInstance().postMultiFile(url, files);
}
}