忽略https证书认证代码:
/**
* 创建模拟客户端(针对 https 客户端禁用 SSL 验证)
* @return
* @throws Exception
*/
public static CloseableHttpClient createHttpClientWithNoSsl() throws Exception {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// don't check
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// don't check
}
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustAllCerts, null);
LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
return HttpClients.custom()
.setSSLSocketFactory(sslSocketFactory)
.build();
}
一、Get请求
接口地址及参数:https://xxx.xxx.com/api/v3/technicians?input_data={“list_info”:{“search_fields”:{“email_id”:“[email protected]”}}}
java代码实现:
OAPropUtil.technician_info_url = https://xxx.xxx.com/api/v3/technicians
String url = OAPropUtil.technician_info_url+"?input_data="+ URLEncoder.encode(JSON.toJSONString(listInfo),"UTF-8");
headerMap.put("authtoken", "12345");
headerMap.put("Content-type", "application/json;charset=UTF-8");
String resultStr = OAUtil.getWithHeaderIgnoreSSL(url,headerMap);
public static String getWithHeaderIgnoreSSL(String url,Map<String, String> headerMap) throws Exception {
CloseableHttpClient httpclient = createHttpClientWithNoSsl();
HttpGet get = new HttpGet(url);
// 设置请求头信息
if (headerMap != null && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
get.addHeader(key, headerMap.get(key));
}
}
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
.setSocketTimeout(20000).setConnectTimeout(3000).build();
get.setConfig(requestConfig);
HttpResponse response = httpclient.execute(get);
try {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
//4.解析响应,获取数据
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity,"UTF-8");
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "]");
}
}
} catch (HttpException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("网络异常!");
}
return null;
}
Map<String, String> param = new HashMap<>();
param.put("input_data", JSON.toJSONString(request));
Map<String,String> itsmHeader = new HashMap<>();
itsmHeader.put("authtoken", "12345");
itsmHeader.put("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
String ticketStr = OAUtil.postWithHeaderIgnoreSSL(url, param, itsmHeader);
public static String postWithHeaderIgnoreSSL(String url, Map<String,String> param, Map<String, String> headerMap) throws Exception {
CloseableHttpClient httpclient = createHttpClientWithNoSsl();
HttpPost post = new HttpPost(url);
// 设置请求头信息
if (headerMap != null && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
post.addHeader(key, headerMap.get(key));
}
}
List<org.apache.http.NameValuePair> nameValuePairList = new ArrayList<>();
if (param != null) {
for (String key : param.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, param.get(key)));
}
}
try {
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
.setSocketTimeout(20000).setConnectTimeout(3000).build();
post.setConfig(requestConfig);
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
//设置请求参数
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
String res = EntityUtils.toString(response.getEntity(),"UTF-8");
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED){
//返回json格式
post.releaseConnection();
return res;
} else {
System.out.println("response《" + res + "》,url[" + url + "],json[" + param + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (post != null)
post.releaseConnection();
if (httpclient != null){
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
HttpClient工具类范例
/*
*
* Copyright (C) 1999-2012 IFLYTEK Inc.All Rights Reserved.
*
* FileName:OAUtil.java
*
* Description:
*
* History:
* Version Author Date Operation
* 1.0 jfzhao 2014年11月4日上午10:41:12 Create
*/
package com.iflytek.oa.util;
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.*;
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.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import weaver.system.code.CodeBuild;
import weaver.workflow.request.RequestManager;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author jfzhao
* @version 1.0
*/
public class OAUtil {
/**
* @param s oa内存储的EASID
* @return easID
* @description 由于OA不允许人员直接挂靠在公司下,
* 所以原EAS中直接挂靠公司的人员归属的部门EASID为EAS公司ID加other字样构成
* @author jfzhao
* @create 2014年11月4日上午10:45:23
* @version 1.0
*/
public static String subEASID(String s) {
if (s.endsWith("other")) {
return s.substring(0, s.length() - "other".length());
} else {
return s;
}
}
/**
* @param requestManager 请求对象
* @description 创建单据编码
* @author jfzhao
* @create 2014年12月4日下午4:16:54
* @version 1.0
*/
public static void createNumber(RequestManager requestManager) {
int formID = requestManager.getFormid();
int isBill = requestManager.getIsbill();
int workFlowID = requestManager.getWorkflowid();
int creater = requestManager.getCreater();
int requestID = requestManager.getRequestid();
int createrType = requestManager.getCreatertype();
CodeBuild cbuild = new CodeBuild(formID, String.valueOf(isBill),
workFlowID, creater, createrType);
cbuild.getFlowCodeStr(requestID, isBill, formID, workFlowID, creater,
createrType);
}
/**
* @param url 地址
* @param valuePairs 参数
* @return 返回的信息
* @throws Exception 异常信息
* @description post方法
* @author zhsong
* @create 2015年11月2日下午4:21:43
* @version 1.0
*/
public static String post(String url, NameValuePair[] valuePairs) throws Exception {
HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.setRequestBody(valuePairs);
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(35000);
try {
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} finally {
//20181119 添加释放连接
postMethod.releaseConnection();
}
return null;
}
public static String authorizationPost(String token, String url, NameValuePair[] valuePairs) throws Exception {
HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.setRequestBody(valuePairs);
postMethod.setRequestHeader("token", token);
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(35000);
try {
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} finally {
//20181119 添加释放连接
postMethod.releaseConnection();
}
return null;
}
public static class UTF8PostMethod extends PostMethod {
public UTF8PostMethod(String url) {
super(url);
}
@Override
public String getRequestCharSet() {
return "UTF-8";
}
}
/**
* @param url
* @param valuePairs
* @return
* @throws Exception
* @desc get方式
* @author chaozhou6
* @date 2018年3月27日 下午10:31:10
*/
public static String get(String url, NameValuePair[] valuePairs) throws Exception {
String params = nameValuePairToString(valuePairs);
HttpClient httpclient = new HttpClient();
GetMethod getMethod = new UTF8GetMethod(url + "?" + params);
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
// 设置返回超时时间(单位毫秒)
managerParams.setSoTimeout(35000);
try {
int statusCode = httpclient.executeMethod(getMethod);
if (statusCode == HttpStatus.SC_OK) {
return getMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("网络异常!");
}
return null;
}
public static String get(String url) throws Exception {
HttpClient httpclient = new HttpClient();
GetMethod getMethod = new UTF8GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
// 设置返回超时时间(单位毫秒)
managerParams.setSoTimeout(20000);
try {
int statusCode = httpclient.executeMethod(getMethod);
if (statusCode == HttpStatus.SC_OK) {
return getMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} catch (IOException e) {
e.printStackTrace();
throw new Exception("网络异常!");
}
return null;
}
/**
* @param valuePairs
* @return
* @desc NameValuePair转为get方式参数
* @author chaozhou6
* @date 2018年3月27日 下午11:09:45
*/
private static String nameValuePairToString(NameValuePair[] valuePairs) {
String params = "";
if (valuePairs != null && valuePairs.length > 0) {
for (NameValuePair nameValuePair : valuePairs) {
params += nameValuePair.getName() + "=" + nameValuePair.getValue() + "&";
}
params = params.substring(0, params.length() - 1);
}
return params;
}
public static class UTF8GetMethod extends GetMethod {
public UTF8GetMethod(String url) {
super(url);
}
@Override
public String getRequestCharSet() {
return "UTF-8";
}
}
/**
* @param logtype
* @return
* @description oa nodetype对应汉字说明
* @author zhsong
* @create 2016年3月23日上午9:38:53
* @version 1.0
*/
public static String getHandle(String logtype) {
if (null != logtype && !"".equals(logtype)) {
String ret = "";
char[] ch = logtype.toCharArray();
if (ch != null && ch.length == 1) {
char t = logtype.toCharArray()[0];
switch (t) {
case '0':
ret = "批准";
break;
case '1':
ret = "保存";
break;
case '2':
ret = "提交";
break;
case '3':
ret = "退回";
break;
case '4':
ret = "重新打开";
break;
case '5':
ret = "删除";
break;
case '6':
ret = "激活";
break;
case '7':
ret = "转发";
break;
case '9':
ret = "批注";
break;
case 'e':
ret = "强制归档";
break;
case 't':
ret = "抄送";
break;
case 's':
ret = "督办";
break;
default:
ret = "";
break;
}
}
return ret;
}
return null;
}
/**
* @param htmlStr
* @return
* @description 过滤
* @author lqxiong
* @create 2016年11月23日上午9:42:36
* @version 1.0
*/
public static String delHTMLTag(String htmlStr) {
if (null == htmlStr) {
return "";
}
String regEx_script = "