java httpclient工具类,支持http、https协议,可绕过ssl证书校验一步,数据格式支持form表单和json

httpclient是java中最常用的http请求工具包,实际工作过程中很多场景我们都会用到,比如:网页抓取、restful接口请求等

而我们要请求的地址可能是http协议,也可能是https协议(https=http+ssl)

此工具类是对httpclient组件的封装,可提供统一的api入口实现对http和https协议接口的访问,支持form表单提交和json格式数据的提交,并可设置请求头等信息

工具类代码:

/**
* httpclient工具类,支持http,https,可绕过ssl证书校验一步
* 基于httpclient4.5.6
* pom.xml引入
* <dependency>
* <groupId>org.apache.httpcomponents</groupId>
* <artifactId>httpclient</artifactId>
* <version>4.5.6</version>
* </dependency>
*
* @author 肖哥
*/
public class HttpClientUtil {
private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
private static final String CHAR_SET = "UTF-8";
private static SSLConnectionSocketFactory sslSocketFactory = null;
private static CloseableHttpClient httpClient = null;
//设置超时时间
private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(2000).setSocketTimeout(10000).build();

static {
try {
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
httpClient = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* post方式请求数据并返回结果
*
* @param url 请求地址
* @return String 结果
*/
public static String doPost(String url) throws Exception {
return doPost(url, null, null, null);
}

/**
* post方式请求数据并返回结果
*
* @param url 请求地址
* @param headers 头信息
* @param formParamMap form参数集合
* @param jsonStr json字符串
* @return String 结果
*/
public static String doPost(String url, Map<String, String> headers, Map<String, String> formParamMap, String jsonStr)
throws Exception {
LOG.info("doPost start : url={};headers={};formParamMap={};jsonStr={}", url, headers, formParamMap, jsonStr);
String result = "";
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 设置头信息
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求参数
if (formParamMap != null && formParamMap.size() > 0) {
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + CHAR_SET);
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : formParamMap.entrySet()) {
// 给参数赋值
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, CHAR_SET);
httpPost.setEntity(urlEncodedFormEntity);
}
// 设置实体 优先级高
if (jsonStr != null && !"".equals(jsonStr)) {
StringEntity jsonEntity = new StringEntity(jsonStr);
jsonEntity.setContentEncoding(CHAR_SET);
jsonEntity.setContentType("application/json");
httpPost.setEntity(jsonEntity);
}
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity, CHAR_SET);
} else {
result = httpResponse.getStatusLine().getStatusCode() + "";
}

} catch (Exception e) {
LOG.error(e.toString());
throw e;
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
LOG.info("result=" + result);
return result;
}

/**
* get方式请求数据并返回结果
*
* @param url 请求地址
* @return String 结果
*/
public static String doGet(String url) throws Exception {
return doGet(url, null, null);
}

/**
* get方式请求数据并返回结果
*
* @param url 请求地址
* @param headers 头信息
* @param formParamMap 参数集合
* @return String 结果
*/
public static String doGet(String url, Map<String, String> headers, Map<String, String> formParamMap) throws Exception {
LOG.info("doGet start : url={};headers={};formParamMap={}", url, headers, formParamMap);
String result = "";
CloseableHttpResponse httpResponse = null;
try {
HttpGet httpGet = new HttpGet();
httpGet.setConfig(requestConfig);
// 设置头信息
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求参数
StringBuffer urlSb = new StringBuffer();
urlSb.append(url);
// 设置请求参数
if (formParamMap != null && formParamMap.size() > 0) {
httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + CHAR_SET);
// 转换为键值对
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : formParamMap.entrySet()) {
// 给参数赋值
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(formparams, CHAR_SET));
urlSb.append("?");
urlSb.append(paramStr);
}
LOG.info("real url=" + urlSb.toString());
httpGet.setURI(URI.create(urlSb.toString()));
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity, CHAR_SET);
} else {
result = httpResponse.getStatusLine().getStatusCode() + "";
}

} catch (Exception e) {
LOG.error(e.toString());
throw e;
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
LOG.info("result=" + result);
return result;
}
}

使用demo代码
public static void main(String[] args) throws Exception {
{
//提交form表单
String url = "http(s)://www.xxx.com";
//请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("h1","xxx");
headers.put("h2","xxx");
//参数
Map<String, String> formParamMap = new HashMap<String, String>();
formParamMap.put("p1", "xxx");
formParamMap.put("p2", "xxx");
String result = HttpClientUtil.doPost(url, headers, formParamMap, null);
System.out.println(result);
}
{
//json数据提交
//提交form表单
String url = "http(s)://www.xxx.com";
//请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("h1","xxx");
headers.put("h2","xxx");
//参数
String jsonStr = "{xxx}";
String result = HttpClientUtil.doPost(url, headers, null, jsonStr);
System.out.println(result);
}
}

猜你喜欢

转载自www.cnblogs.com/xgmnrj/p/9449985.html
今日推荐