package cn.com.goldenwater.dcproj.utils; import com.alibaba.fastjson.JSONObject; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; 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.HttpRequestBase; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 用于处理get/post提交请求 */ public class HttpClientUtils { /** * httpclient读取内容时使用的字符集 */ public static final String CONTENT_CHARSET = "UTF-8"; public static final Charset UTF_8 = Charset.forName("UTF-8"); public static final Charset GBK = Charset.forName(CONTENT_CHARSET); /** * 简单get调用 * * @param url * @param params * @return * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ public static String simpleGetInvoke(String url, Map params) throws Exception { return simpleGetInvoke(url, params, CONTENT_CHARSET); } /** * 简单get调用 * * @param url * @param params * @return * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ public static String simpleGetInvoke(String url, Map params, String charset) throws ClientProtocolException, IOException, URISyntaxException { HttpClient client = buildHttpClient(false); HttpGet get = buildHttpGet(url, params); HttpResponse response = client.execute(get); assertStatus(response); HttpEntity entity = response.getEntity(); if (entity != null) { String returnStr = EntityUtils.toString(entity, charset); return returnStr; } return null; } /** * 简单get调用 * * @param url * @param params * @return * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ public static String simpleGetInvoke(String url, Map params, Map headerMap, String charset) throws ClientProtocolException, IOException, URISyntaxException { HttpClient client = buildHttpClient(false); HttpGet get = buildHttpGet(url, params); //添加header信息 if (headerMap != null && !headerMap.isEmpty()) { for (String key : headerMap.keySet()) { get.setHeader(key, headerMap.get(key)); } } HttpResponse response = client.execute(get); assertStatus(response); HttpEntity entity = response.getEntity(); if (entity != null) { String returnStr = EntityUtils.toString(entity, charset); return returnStr; } return null; } /** * 简单post调用 * * @param url * @param params * @return * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ public static String simplePostInvoke(String url, Map params) throws Exception { return simplePostInvoke(url, params, CONTENT_CHARSET); } /** * 简单post调用 * * @param url * @param params * @return * @throws URISyntaxException * @throws ClientProtocolException * @throws IOException */ public static String simplePostInvoke(String url, Map params, String charset) throws URISyntaxException, ClientProtocolException, IOException { HttpClient client = buildHttpClient(false); HttpPost postMethod = buildHttpPost(url, params); HttpResponse response = client.execute(postMethod); assertStatus(response); HttpEntity entity = response.getEntity(); if (entity != null) { String returnStr = EntityUtils.toString(entity, charset); return returnStr; } return null; } /** * 创建HttpClient * * @param isMultiThread * @return */ public static HttpClient buildHttpClient(boolean isMultiThread) { CloseableHttpClient client; if (isMultiThread) { client = HttpClientBuilder .create() .setConnectionManager( new PoolingHttpClientConnectionManager()).build(); } else { client = HttpClientBuilder.create().build(); // 设置代理服务器地址和端口 } return client; } /** * 构建httpPost对象 * * @param url * @return * @throws UnsupportedEncodingException * @throws URISyntaxException */ public static HttpPost buildHttpPost(String url, Map params) throws UnsupportedEncodingException, URISyntaxException { HttpPost post = new HttpPost(url); setCommonHttpMethod(post); HttpEntity he = null; if (params != null) { List formparams = new ArrayList(); for (String key : params.keySet()) { formparams.add(new BasicNameValuePair(key, params.get(key))); } he = new UrlEncodedFormEntity(formparams, GBK); post.setEntity(he); } return post; } /** * 构建httpGet对象 * * @param url * @return * @throws URISyntaxException */ public static HttpGet buildHttpGet(String url, Map params) throws URISyntaxException { HttpGet get = new HttpGet(buildGetUrl(url, params)); return get; } /** * build getUrl str * * @param url * @param params * @return */ private static String buildGetUrl(String url, Map params) { StringBuffer uriStr = new StringBuffer(url); if (params != null) { List ps = new ArrayList(); for (String key : params.keySet()) { ps.add(new BasicNameValuePair(key, params.get(key))); } uriStr.append("?"); uriStr.append(URLEncodedUtils.format(ps, UTF_8)); } return uriStr.toString(); } /** * 设置HttpMethod通用配置 * * @param httpMethod */ public static void setCommonHttpMethod(HttpRequestBase httpMethod) { httpMethod.setHeader(HTTP.CONTENT_ENCODING, CONTENT_CHARSET);// setting } /** * 强验证必须是200状态否则报异常 * * @param res * @throws HttpException */ static void assertStatus(HttpResponse res) throws IOException { System.out.println(res.getStatusLine().getStatusCode()); switch (res.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: break; default: throw new IOException("服务器响应状态异常,失败."); } } public static String doHttpsPost(String url, Map map, Map headerMap) { HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try { httpClient = new SSLClient(); httpPost = new HttpPost(url); //添加header信息 if (headerMap != null && !headerMap.isEmpty()) { for (String key : headerMap.keySet()) { httpPost.setHeader(key, headerMap.get(key)); } } //设置参数 List list = new ArrayList(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry elem = (Map.Entry) iterator.next(); list.add(new BasicNameValuePair(elem.getKey(), elem.getValue())); } if (list.size() > 0) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, CONTENT_CHARSET); httpPost.setEntity(entity); } HttpResponse response = httpClient.execute(httpPost); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, CONTENT_CHARSET); } } } catch (Exception ex) { ex.printStackTrace(); } return result; } public static String doHttpsPost2(String url, Map map, Map headerMap) { HttpClient httpClient = null; HttpPost httpPost = null; String result = null; headerMap.put("Content-Type", "application/json;charset=utf8"); try { httpClient = new SSLClient(); httpPost = new HttpPost(url); //添加header信息 if (headerMap != null && !headerMap.isEmpty()) { for (String key : headerMap.keySet()) { httpPost.setHeader(key, headerMap.get(key)); } } //设置参数 String jsonString = JSONObject.toJSONString(map); StringEntity entity = new StringEntity(jsonString, CONTENT_CHARSET); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, CONTENT_CHARSET); } } } catch (Exception ex) { ex.printStackTrace(); } return result; } }