说明:没有使用工具类的方式是为了封装
public class HttpClientService {
private static final String DEFAULT_CHARSET = "UTF-8";
private CloseableHttpClient httpclient;
private CookieStore cookieStore;
private HttpClientContext localContext;
private String charset;
private static final String FILE_COLUMN = "fileColumn";
public HttpClientService() {
httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
cookieStore = new BasicCookieStore();
localContext = HttpClientContext.create();
// Bind custom cookie store to the local context
localContext.setCookieStore(cookieStore);
this.charset = DEFAULT_CHARSET;
}
public HttpClientService(String charset) {
httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
cookieStore = new BasicCookieStore();
localContext = HttpClientContext.create();
// Bind custom cookie store to the local context
localContext.setCookieStore(cookieStore);
this.charset = charset;
}
public void closeHttpClient() {
IOUtils.closeQuietly(httpclient);
}
public void login(String url, Map<String, String> params) throws IOException {
this.doPost(url, params);
}
public String doGet(String url) throws Exception {
return this.doGet(url, null, null);
}
public String doGet(String url, Map<String, String> params) throws Exception {
return this.doGet(url, params, null);
}
public String doGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException, URISyntaxException {
if (MapUtils.isNotEmpty(params)) {
URIBuilder uriBuilder = new URIBuilder(url);
Set<String> keySet = params.keySet();
for (String key : keySet) {
uriBuilder.addParameter(key, params.get(key));
}
url = uriBuilder.build().toString();
}
HttpGet httpget = new HttpGet(url);
setHeaders(headers, httpget);
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
return this.getResult(response);
}
public String doPost(String url, Map<String, String> params) throws ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(url);
return this.doModify(httpPost, params);
}
/**
*根据不同的ContentType提交请求
*/
public String postVariable(String url, String str,String contentType,String charset) throws Exception {
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(str,charset);
entity.setContentType(contentType);
entity.setContentEncoding(charset);
post.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(post);
return getResult(response);
}
public String doPut(String url, Map<String, String> params) throws IOException {
HttpPut httpPut = new HttpPut(url);
return this.doModify(httpPut, params);
}
public String doDelete(String url, Map<String, String> params) throws IOException {
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
return this.doModify(httpDelete, params);
}
private String doModify(HttpEntityEnclosingRequestBase requestBase, Map<String, String> params) throws IOException {
List<NameValuePair> parametersList = new ArrayList<>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
NameValuePair parameters = new BasicNameValuePair(key, params.get(key));
parametersList.add(parameters);
}
requestBase.setEntity(new UrlEncodedFormEntity(parametersList, DEFAULT_CHARSET));
CloseableHttpResponse response = httpclient.execute(requestBase, localContext);
final List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie : cookies) {
log.info(cookie.getName() + ":" + cookie.getValue());
}
return this.getResult(response);
}
public static String getResult(CloseableHttpResponse response) throws ParseException, IOException {
try {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
String result = entity != null ? EntityUtils.toString(entity, DEFAULT_CHARSET) : null;
EntityUtils.consume(entity);
return result;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
} finally {
IOUtils.closeQuietly(response);
}
}
public String doPostFile(String url, File file) throws IOException {
HttpPost httpPost = new HttpPost(url);
return this.doModifyFile(httpPost, file);
}
private String doModifyFile(HttpEntityEnclosingRequestBase requestBase, File file)
throws ParseException, IOException {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder = multipartEntityBuilder.addBinaryBody(FILE_COLUMN, file);
HttpEntity httpEntity = multipartEntityBuilder.build();
requestBase.setEntity(httpEntity);
CloseableHttpResponse response = httpclient.execute(requestBase, localContext);
return this.getResult(response);
}
/**
* 设置头信息
* @param headers
* @param httpRequestBase
*/
private static void setHeaders(Map<String, String> headers, HttpRequestBase httpRequestBase) {
if (MapUtils.isNotEmpty(headers)) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpRequestBase.setHeader(entry.getKey(), entry.getValue());
}
}
}
}