java程序 apache.http请求 GET/POST 设置代理与不代理 TLSv1协议

在java程序中。使用http请求是十分常见的事情,本文将介绍如何使用apache包的httpClient处理工具类。
(转载请标明出处©)
正文介绍:
项目使用maven,在pom.xml文件中引入jar包。如图所示
java程序 apache.http请求 GET/POST 设置代理与不代理 TLSv1协议_第1张图片
使用工具类HttpUtil类如图所示
java程序 apache.http请求 GET/POST 设置代理与不代理 TLSv1协议_第2张图片
以下贴出代码片段


            org.apache.httpcomponents
            httpclient
            4.5.9
        
        
            com.alibaba
            fastjson
            1.2.47
        
package com.alone.myproject.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 

Description: [apache包http请求工具类]

* @author 恋雨烟梦 * @version 1.0 * Copyright (c) 2019 恋雨烟梦© */ public class HttpUtil { /**默认编码字符集*/ private static final String DEFAULTCHARSET = "utf-8"; /**空值判断正则*/ private static final String ISNULLREGULAR = "^\\s*$"; /**HTTP隔离符*/ private static final Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL); /**连接符*/ private static final String CONNECTOR = "?"; /**TLSv1协议*/ private static final String TCP_TLSv1 = "TLSv1"; /**请求连接时间*/ private static final int SOCKETTIMEOUT = 5000; /**请求连接时间*/ private static final int CONNECTTIMEOUT = 5000; /**数值为6*/ private static final int SIX = 6; /**数值为0*/ private static final int ZERO = 0; /**HTTP默认请求头*/ private static final String ACCEPTENCODING = "gzip, deflate, br"; /**HTTP默认请求头*/ private static final String ACCEPTLANGUAGE = "zh-CN,zh;q=0.9"; /**HTTP默认请求头*/ private static final String CONNECTION = "keep-alive"; /**HTTP默认请求头*/ private static final String CROSSREQUESTOPENSIGN = "1"; /**HTTP默认请求头*/ private static final String ACCEPT = "application/json"; /**HTTP默认请求头*/ private static final String CONTENTTYPE = "application/json; charset=utf-8"; /**HTTP默认请求头*/ private static final String USERAGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"; /** * Description: [字符串转码] * @param param 参数 * @param charset 字符编码集-若为空,则默认utf-8 * @return: java.lang.String * Created on 2019年09月19日 * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static String getEncoderCharset(String param, String charset){ if (isNull(param)) { return null; } if (isNull(charset)) { charset = DEFAULTCHARSET; } try { return URLEncoder.encode(param, charset); } catch (UnsupportedEncodingException e) { return null; } } /** * Description: [删除目标字符串中的http标记符] * @param param 目标字符串 * @return: java.lang.String * Created on 2019年09月19日 * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static String delHtml(String param) { if (isNull(param)) { return null; } Matcher matcher =pattern.matcher(param); String name =matcher.replaceAll(""); return name; } /** * Description: [获取默认HTTP协议Client] * @param * @return: org.apache.http.impl.client.CloseableHttpClient * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static CloseableHttpClient getDefaultClient() { return HttpClients.createDefault(); } /** * Description: [获取代理设置HTTP协议Client] * @param proxyHost 代理主机 * @param proxyPort 代理端口 * @param proxyName 代理服务用户名 * @param proxyPwd 代理服务密码 * @return: org.apache.http.impl.client.CloseableHttpClient * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static CloseableHttpClient getProxyClient(String proxyHost, int proxyPort, String proxyName, String proxyPwd) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(proxyName, proxyPwd)); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build(); return httpClient; } /** * Description: [获取TLSv1协议Client] * @param * @return: org.apache.http.impl.client.CloseableHttpClient * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static CloseableHttpClient getTLSv1Client(){ try { SSLConnectionSocketFactory sslsf = getTLSv1(); CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return client; } catch (Exception e) { return HttpClients.createDefault(); } } /** * Description: [获取代理设置TLSv1协议Client] * @param proxyHost 代理主机 * @param proxyPort 代理端口 * @param proxyName 代理服务用户名 * @param proxyPwd 代理服务密码 * @return: org.apache.http.impl.client.CloseableHttpClient * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static CloseableHttpClient getProxyTLSv1Client(String proxyHost, int proxyPort, String proxyName, String proxyPwd) { try { SSLConnectionSocketFactory sslsf = getTLSv1(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(proxyName, proxyPwd)); CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(provider).build(); return client; } catch (Exception e) { return getProxyClient(proxyHost, proxyPort, proxyName, proxyPwd); } } /** * Description: [获取默认Config面板] * @param * @return: org.apache.http.client.config.RequestConfig * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static RequestConfig getDefaultConfig() { return RequestConfig.custom().setSocketTimeout(SOCKETTIMEOUT).setConnectTimeout(CONNECTTIMEOUT).build(); } /** * Description: [获取代理设置Config面板] * @param proxyHost 代理主机 * @param proxyPort 代理端口 * @return: org.apache.http.client.config.RequestConfig * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static RequestConfig getProxyConfig(String proxyHost, int proxyPort) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); return RequestConfig.custom().setSocketTimeout(SOCKETTIMEOUT).setConnectTimeout(CONNECTTIMEOUT).setProxy(proxy).build(); } /** * Description: [获取默认http请求头信息] * @param * @return: java.util.Map * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static Map getDefaultHeadsParams() { Map headsParams = new HashMap(SIX); headsParams.put("Accept-Encoding", ACCEPTENCODING); headsParams.put("Accept-Language", ACCEPTLANGUAGE); headsParams.put("Connection", CONNECTION); headsParams.put("cross-request-open-sign", CROSSREQUESTOPENSIGN); headsParams.put("Accept", ACCEPT); headsParams.put("Content-type", CONTENTTYPE); headsParams.put("User-Agent", USERAGENT); return headsParams; } /** * Description: [GET请求-均使用默认Client与默认Config与默认heads参数面板] * @param url 请求地址 * @param params 请求参数 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static String getHttp(String url, Map params) { if (isNull(url)) { return sysError("地址为空"); } try { CloseableHttpClient client = getDefaultClient(); RequestConfig config = getDefaultConfig(); String resp = httpGet(url, params, client, config, getDefaultHeadsParams()); return resp; } catch (Exception e) { return sysError(e); } } /** * Description: [GET请求-使用指定Client与指定Config与指定heads参数面板] * @param url 请求地址 * @param params 参数面板 * @param client 指定Client-若为空,默认为getDefaultClient() * @param config 指定Config-若为空,getDefaultConfig() * @param headsParams 指定heads参数面板-若为空,默认为getDefaultHeadsParams() * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static String getHttp(String url, Map params, CloseableHttpClient client, RequestConfig config, Map headsParams) { if (isNull(url)) { return sysError("地址为空"); } try { CloseableHttpClient httpClient = (client == null ? getDefaultClient() : client); RequestConfig requestConfig = (config == null ? getDefaultConfig() : config); Map heads = (headsParams == null ? getDefaultHeadsParams() : headsParams); String resp = httpGet(url, params, httpClient, requestConfig, heads); return resp; } catch (Exception e) { return sysError(e); } } /** * Description: [POST请求(JSON数据请求)-均使用默认Client与默认Config与默认heads参数面板] * @param url 请求地址 * @param params 参数面板 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static String postHttpJson(String url, Map params) { if (isNull(url)) { return sysError("地址为空"); } try { CloseableHttpClient client = getDefaultClient(); RequestConfig config = getDefaultConfig(); String resp = httpPost(url, params, client, config, getDefaultHeadsParams()); return resp; } catch (Exception e) { return sysError(e); } } /** * Description: [POST请求(JSON数据请求)-使用指定Client与指定Config与指定heads参数面板] * @param url 请求地址 * @param params 参数面板 * @param client 指定Client-若为空,默认为getDefaultClient() * @param config 指定Config-若为空,getDefaultConfig() * @param headsParams 指定heads参数面板-若为空,默认为getDefaultHeadsParams() * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ public static String postHttpJson(String url, Map params, CloseableHttpClient client, RequestConfig config, Map headsParams) { if (isNull(url)) { return sysError("地址为空"); } try { CloseableHttpClient httpClient = (client == null ? getDefaultClient() : client); RequestConfig requestConfig = (config == null ? getDefaultConfig() : config); Map heads = (headsParams == null ? getDefaultHeadsParams() : headsParams); String resp = httpPost(url, params, httpClient, requestConfig, heads); return resp; } catch (IOException e) { return sysError(e); } } /** * Description: [HTTP-GET请求] * @param url 请求地址 * @param params 请求参数 * @param client client服务 * @param config config参数面板 * @param headsParams 请求头信息 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String httpGet(String url, Map params, CloseableHttpClient client, RequestConfig config, Map headsParams) throws IOException { HttpGet request = new HttpGet(getHttpUrl(url, params)); request.setConfig(config); convertHeadsParams(request, headsParams); CloseableHttpResponse response = client.execute(request); String result = getHttpResp(response); return result; } /** * Description: [HTTP-POST请求] * @param url 请求地址 * @param params 请求参数 * @param client client服务 * @param config config参数面板 * @param headsParams 请求头信息 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String httpPost(String url, Map params, CloseableHttpClient client, RequestConfig config, Map headsParams) throws IOException { StringEntity stringEntity = new StringEntity(convertParamsJSON(params), DEFAULTCHARSET); stringEntity.setContentEncoding(DEFAULTCHARSET); HttpPost request = new HttpPost(url); request.setConfig(config); convertHeadsParams(request, headsParams); request.setEntity(stringEntity); CloseableHttpResponse response = client.execute(request); String result = getHttpResp(response); return result; } /** * Description: [系统错误] * @param errorMsg 错误信息 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String sysError(String errorMsg) { return httpResp("-1", errorMsg, null); } /** * Description: [系统错误] * @param e 异常 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String sysError(Exception e) { return httpResp("-1", "请求发生系统错误", getExceptionToString(e)); } /** * Description: [返回值字符串格式化] * @param httpCode http状态码 * @param errorMsg 错误描述 * @param data 响应字符集 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String httpResp(String httpCode, String errorMsg, String data) { StringBuilder strbuf = new StringBuilder(); strbuf.append("{").append("httpCode:").append(httpCode).append(",").append("errorMsg:").append(errorMsg).append(",").append("data:").append(data).append("}"); return strbuf.toString(); } /** * Description: [请求返回值] * @param response 请求响应 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String getHttpResp(CloseableHttpResponse response) throws IOException { int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String resp = EntityUtils.toString(entity, DEFAULTCHARSET); return httpResp(String.valueOf(statusCode), null, resp); } /** * Description: [设置头信息] * @param request 请求头 * @param headsParams 参数 * @return: void * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static void convertHeadsParams(HttpGet request, Map headsParams) { if (request == null || headsParams == null || headsParams.size() == ZERO) { return; } for (String key : headsParams.keySet()) { request.setHeader(key, headsParams.get(key)); } } /** * Description: [设置头信息] * @param request 请求头 * @param headsParams 参数 * @return: void * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static void convertHeadsParams(HttpPost request, Map headsParams) { if (request == null || headsParams == null || headsParams.size() == ZERO) { return; } for (String key : headsParams.keySet()) { request.setHeader(key, headsParams.get(key)); } } /** * Description: [参数JSON] * @param params 参数 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String convertParamsJSON(Map params) { return JSON.toJSONString(params); } /** * Description: [GET请求参数处理] * @param url 请求地址 * @param params 参数 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String getHttpUrl(String url, Map params) { if (params == null || params.size() == ZERO) { return url; } int flag = url.indexOf(CONNECTOR); StringBuilder buf = new StringBuilder(); buf.append(url); if (flag == -1) { buf.append("?"); } int i = ZERO; for (String key : params.keySet()) { if (i > ZERO) { buf.append("&"); } buf.append(key).append("=").append(params.get(key)); i++; } return buf.toString(); } /** * Description: [获取TLSv1协议面板] * @param * @return: org.apache.http.conn.ssl.SSLConnectionSocketFactory * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static SSLConnectionSocketFactory getTLSv1() throws NoSuchAlgorithmException, KeyManagementException { X509TrustManager trustManager = getX509TrustManager(); SSLContext sc = SSLContext.getInstance(TCP_TLSv1); sc.init(null, new TrustManager[] { trustManager }, null); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sc); return sslsf; } /** * Description: [跳过安全证书] * @param * @return: javax.net.ssl.X509TrustManager * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static X509TrustManager getX509TrustManager() { X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; return trustManager; } /** * Description: [空值判断] * @param param 参数 * @return: boolean * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static boolean isNull(String param) { if (param == null) { return true; } return param.matches(ISNULLREGULAR); } /** * Description: [异常打印] * @param e 异常信息 * @return: java.lang.String * @version 1.0 * Copyright (c) 2019 恋雨烟梦© **/ private static String getExceptionToString(Exception e) { if (e == null) { return ""; } StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } /**工具类禁止new创建*/ private HttpUtil(){} }

你可能感兴趣的:(java)