/** * Created by sunlei on 2016/12/24 0024. */ import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.config.CookieSpecs; 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.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; import java.io.IOException; import java.nio.charset.Charset; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 封装httpCilent请求,基于httpClient4.5.2开发 * HTTP请求工具类 */ public class HttpUtil { private static PoolingHttpClientConnectionManager connectionManager; private static RequestConfig requestConfig; private static final int MAX_TIMEOUT = 5 * 1000; /**----------静态模块加载,主要是设置HttpClient的一些属性----------*/ static { //注册http和https Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create() .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", createSSLConnectionSocketFactory()).build(); //设置连接池 connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); //设置连接池大小 connectionManager.setMaxTotal(100); connectionManager.setDefaultMaxPerRoute(100); //(同一个路由允许最大连接数) RequestConfig.Builder configBuilder = RequestConfig.custom(); //设置连接超时 configBuilder.setConnectTimeout(MAX_TIMEOUT); //设置读取超时 configBuilder.setSocketTimeout(MAX_TIMEOUT); //设置从连接池获取连接实例的超时 configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT); //此处使用默认的Cookie规范,可以让后续请求共享Cookie configBuilder.setCookieSpec(CookieSpecs.DEFAULT); //支持重定向 configBuilder.setRedirectsEnabled(true); requestConfig = configBuilder.build(); HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setRedirectStrategy(new LaxRedirectStrategy()) .setSSLSocketFactory(createSSLConnectionSocketFactory()) //设置证书 // .setProxy(new HttpHost("127.0.0.1",8888)) //设置走代理 方便Fiddler查看抓取请求 .build(); } /** * Get方式请求 * * @param Url */ public static String doGet(String Url) { return doGet(Url, null, null); } /** * Get方式请求 * * @param Url * @param map 请求参数 * @param headers */ public static String doGet(String Url, Map<String, Object> map, Map<String, String> headers) { String html = null; String apiUrl = Url; StringBuffer stringBuffer = new StringBuffer(); int flag = 0; //?标识符 /**----------设置请求参数------------*/ if (map!=null&&map.size() != 0) { for (String mapName : map.keySet()) { if (flag == 0) { stringBuffer.append("?"); } else { stringBuffer.append(mapName).append("=").append(map.get(mapName).toString()); flag++; } } } apiUrl += stringBuffer; HttpGet get = new HttpGet(apiUrl); /**----------设置请求头信息-----------*/ if (headers!=null&&headers.size() != 0) { for (String headerName : headers.keySet()) { get.addHeader(headerName, headers.get(headerName)); } } CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpResponse httpResponse = httpClient.execute(get); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { html = EntityUtils.toString(entity,"utf-8"); } } catch (IOException e) { e.printStackTrace(); } return html; } /** * Post方式请求 * * @param Url * @param map * @param headers */ public static String doPost(String Url, Map<String, Object> map, Map<String, String> headers) { String html = null; String apiUrl = Url; CloseableHttpClient httpClient = HttpClients.createDefault(); try { if (map!=null&&map.size() != 0) { HttpPost post = new HttpPost(apiUrl); List<NameValuePair> list = new ArrayList<NameValuePair>(map.size()); /**----------设置请求参数------------*/ for (Map.Entry<String, Object> entry : map.entrySet()) { NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString()); list.add(pair); } /**----------设置请求头信息----------*/ if(headers!=null&&headers.size()!=0) { for (Map.Entry<String, String> entry : headers.entrySet()) { post.addHeader(entry.getKey(),entry.getValue()); } } post.setEntity(new UrlEncodedFormEntity(list, Charset.forName("utf-8"))); HttpResponse httpResponse = httpClient.execute(post); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { html = EntityUtils.toString(entity,"utf-8"); } } } catch(Exception e){ e.printStackTrace(); } return html; } /** * Post方式请求 * * @param Url * @param json * @param json */ public static String doPost(String Url,Object json,Map<String,String> headers){ String html = null; try { HttpPost post = new HttpPost(Url); StringEntity stringEntity = new StringEntity(json.toString(),"utf-8"); stringEntity.setContentType("application/json"); stringEntity.setContentEncoding("utf-8"); post.setEntity(stringEntity); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpResponse httpResponse = httpClient.execute(post); HttpEntity entity = httpResponse.getEntity(); html = EntityUtils.toString(entity,"utf-8"); } catch (Exception e) { e.printStackTrace(); } return html; } /** * 创建SSL连接 * 解决https问题 * */ public static SSLConnectionSocketFactory createSSLConnectionSocketFactory(){ SSLConnectionSocketFactory factory = null; try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return false; } }).build(); factory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); } catch (Exception e) { e.printStackTrace(); } return factory; } }
封装HttpClient工具类;转载请标明出处
最新推荐文章于 2023-11-09 11:24:03 发布