忽略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”:“wjjia@iflytek.com”}}}
postman调用示例:
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;
}
post示例一:
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 = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符
Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
Matcher m_space = p_space.matcher(htmlStr);
htmlStr = m_space.replaceAll(""); // 过滤空格回车换行符
htmlStr = htmlStr.replaceAll(" ", " ");
// 返回文本字符串
return htmlStr.trim();
}
/**
* desc OA远程调用接口方法
* author mhhuang2
*
* @param url 接口地址
* @param nameValuePairs 接口参数
* @return
* @throws
* @date 2017年6月5日 下午3:36:50
*/
public static String remoteInvoke(String url, NameValuePair[] nameValuePairs) {
String result = null;
try {
result = post(url, nameValuePairs);
} catch (Exception e) {
e.printStackTrace();
}
if (null != result) {
result = result.trim();
}
return result;
}
/**
* @param authenticationCode (new sun.misc.BASE64Encoder()).encode("用户名:密码".getBytes())
* @param url 访问地址
* @param jsonContent json串
* @return
* @description 基于HttpClient的Basic认证方案的Patch请求方式
* @author ckyang
* @create 2017年6月21日上午10:46:08
* @version 1.0
*/
public static Map<String, String> BasicAuthorizationPatch(String authenticationCode, String url, String jsonContent) {
Map<String, String> map = new HashMap<String, String>();
String responseResult = "";
String exceptionMessage = "";
int statusCode = 404;
HttpClient httpClient = new HttpClient();
PostMethod method = new UTF8PostMethod(url);
// RequestEntity requestEntity = new StringRequestEntity(text); //中文乱码
RequestEntity requestEntity = null;
try {
requestEntity = new StringRequestEntity(jsonContent, "application/vnd.oracle.adf.resourceitem+json", "UTF-8");
// requestEntity = new StringRequestEntity(jsonContent, "application/vnd.oracle.adf.resourceitem+json", "iso-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
method.setRequestEntity(requestEntity);
method.setRequestHeader("x-http-method-override", "PATCH"); //patch方式访问需要加这个设置,post访问方式不加这个设置
//application/vnd.oracle.adf.action+json
//application/vnd.oracle.adf.resourceitem+json
// method.setRequestHeader("Content-Type","application/vnd.oracle.adf.action+json");
method.setRequestHeader("Content-Type", "application/vnd.oracle.adf.resourceitem+json");
//用户名密码:YANGHONGBO:Hand1234
// method.setRequestHeader("Authorization", " Basic " + (new sun.misc.BASE64Encoder()).encode("YANGHONGBO:Hand1234".getBytes()));
method.setRequestHeader("Authorization", " Basic " + authenticationCode);
try {
statusCode = httpClient.executeMethod(method);
//responseResult = method.getResponseBodyAsString(); //中文乱码
String charset = "UTF-8";
InputStream ins = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(ins, charset)); //按指定的字符集构建文件流
StringBuffer sbf = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sbf.append(line);
}
br.close();
responseResult = sbf.toString().trim();
} catch (Exception e) {
exceptionMessage = e.getMessage();
e.printStackTrace();
}
map.put("responseResult", responseResult);
map.put("exceptionMessage", exceptionMessage);
map.put("statusCode", statusCode + "");
map.put("statusText", HttpStatus.getStatusText(statusCode));
return map;
}
/**
* @param authStr OA调用CRM接口认证用户名/参数
* @param destUrl 访问地址
* @param postData soap串
* @return
* @description 通过soap方式传输数据
* @author lqxiong
* @create 2017年8月9日16:46:33
* @version 1.0
*/
public static Map<String, String> httpPost(String destUrl, String postData, String authStr) throws Exception {
Map<String, String> response = new HashMap<String, String>();
int responseCode = 404;
String responseMessage = "网络异常";
URL url = new URL(destUrl);
HttpURLConnection.setFollowRedirects(true);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (null != conn) {
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// conn.setFollowRedirects(true);
conn.setAllowUserInteraction(false);
conn.setRequestMethod("POST");
//byte[] authBytes = authStr.getBytes("UTF-8");
//String auth = com.sun.org.apache.xml.internal.security.utils.Base64.encode(authBytes);
//conn.setRequestProperty("Authorization", "Basic " + auth);
if (StringUtils.isNotBlank(authStr)) {
conn.setRequestProperty("Authorization", "Basic " + authStr);
}
OutputStream out = conn.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
writer.write(postData);
writer.close();
out.close();
responseCode = conn.getResponseCode();
// System.out.println("connection status: " + conn.getResponseCode());
// System.out.println("connection response: " + conn.getResponseMessage());
InputStream in = conn.getInputStream();
InputStreamReader iReader = new InputStreamReader(in, "UTF-8");
BufferedReader bReader = new BufferedReader(iReader);
String line;
responseMessage = "";
while ((line = bReader.readLine()) != null) {
responseMessage += line;
}
iReader.close();
bReader.close();
in.close();
conn.disconnect();
}
response.put("responseCode", String.valueOf(responseCode));
response.put("responseMessage", responseMessage);
return response;
}
/**
* @param url
* @param json
* @return
* @desc post方式
* @author chaozhou6
* @date 2017年11月13日 上午10:34:22
*/
public static String post(String url, String json) {
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(90000);
RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return null;
}
/**
* 同步PS请求
*
* @param url
* @param json
* @return
* @author junliang3
* @date 2022/2/17 10:23
*/
public static String postForPS(String url, String json) {
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(90000);
RequestEntity requestEntity = new StringRequestEntity(json, "text/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return null;
}
/**
* @param token
* @param url
* @param json
* @return
* @description 向大E传递数据
*/
public static String authorizationHttpPost(String token, String url, String json) {
HttpClient httpClient = new HttpClient();
PostMethod method = new UTF8PostMethod(url);
try {
HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(20000);
RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
method.setRequestEntity(requestEntity);
method.setRequestHeader("Authorization", "Bearer " + token);
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_OK) {
return method.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
return null;
}
public static String httpPostHead(String token, String url, String json) {
HttpClient httpClient = new HttpClient();
PostMethod method = new UTF8PostMethod(url);
try {
HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(20000);
RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
method.setRequestEntity(requestEntity);
method.setRequestHeader("Authorization", token);
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_OK) {
return method.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
return null;
}
/**
* @param url
* @return
* @description
* @author lqxiong
* @create 2018年7月11日下午6:06:36
* @version 1.0
*/
public static String post(String url) {
try {
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new UTF8PostMethod(url);
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "]");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param workcode
* @return
* @desc 员工工号转换
* @author chaozhou6
* @date 2017年11月6日 下午12:22:26
*/
public static String workcodeConversion(String workcode) {
String workcodeTemp = "";
workcodeTemp = workcode.replace("BD", "BEST");
workcodeTemp = workcodeTemp.replace("JD", "WHJD");
workcodeTemp = workcodeTemp.replace("BB", "BBXF");
workcodeTemp = workcodeTemp.replace("BZ", "BZXF");
workcodeTemp = workcodeTemp.replace("FY", "FYSM");
workcodeTemp = workcodeTemp.replace("HB", "HBXF");
workcodeTemp = workcodeTemp.replace("HN", "HNXF");
workcodeTemp = workcodeTemp.replace("JL", "JLKX");
workcodeTemp = workcodeTemp.replace("SZ", "SZXF");
workcodeTemp = workcodeTemp.replace("XY", "XYXF");
workcodeTemp = workcodeTemp.replace("JC", "XFJC");
return workcodeTemp;
}
/**
* @return
* @description 将多个oaid按照域账号顺序排序
* @author lqxiong
* @create 2018年3月29日下午3:40:51
* @version 1.0
*/
public static String sortoaIds(String loginIds, Map<String, String> oaIdsMap) {
String oaIds = "";
if (StringUtils.isNotBlank(loginIds)) {
String[] loginIdsArray = loginIds.split(",");
if (null != oaIdsMap && !oaIdsMap.isEmpty()) {
String temp = "";
for (int i = 0; i < loginIdsArray.length; i++) {
//按照传入的域账号顺序,取出oaid
temp = loginIdsArray[i];
if (null != oaIdsMap.get(temp) && !oaIdsMap.get(temp).isEmpty()) {
oaIds += oaIdsMap.get(temp) + ",";
}
}
oaIds = oaIds.substring(0, oaIds.length() - 1);
}
}
return oaIds;
}
/**
* @param url
* @param json
* @return
* @desc post方式
* @author chaozhou6
* @date 2017年11月13日 上午10:34:22
*/
public static String postWithResultCharset(String url, String json) {
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(20000);
RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return null;
}
/**
* @param url
* @param valuePairs
* @return
* @throws Exception
* @desc get方式
* @author chaozhou6
* @date 2018年3月27日 下午10:31:10
*/
public static String getWithResultCharset(String url, NameValuePair[] valuePairs) throws Exception {
String params = nameValuePairToString(valuePairs);
HttpClient httpclient = new HttpClient();
GetMethod getMethod = new UTF8GetMethod(url + "?" + params);
getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
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;
}
/**
* get请求携带请求头
*
* @param url 地址
* @param valuePairs 参数
* @param headerMap 请求头信息
* @return String
* @throws Exception
* @desc get方式
* @author lewang4
* @date 2021-12-03
*/
public static String getWithHeader(String url, NameValuePair[] valuePairs, Map<String, String> headerMap) throws Exception {
String params = nameValuePairToString(valuePairs);
HttpClient httpclient = new HttpClient();
GetMethod getMethod = new UTF8GetMethod(url + "?" + params);
// 设置请求头信息
if (headerMap != null && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
getMethod.setRequestHeader(key, headerMap.get(key));
}
}
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
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;
}
/**
* post方法
*
* @param url 地址
* @param json 参数
* @param headerMap 请求头信息
* @return 返回的信息
* @author zhsong
* @create 2015年11月2日下午4:21:43
*/
public static String postWithHeader(String url, String json, Map<String, String> headerMap) {
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new UTF8PostMethod(url);
// 设置请求头信息
if (headerMap != null && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
postMethod.setRequestHeader(key, headerMap.get(key));
}
}
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(20000);
RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return null;
}
/**
* 反写OTC系统
*
* @param url 地址
* @param json 数据
* @return string
* @author junliang3
* @date 2022/5/24 10:39
*/
public static String postToOTC(String url, String json) {
HttpClient httpclient = new HttpClient();
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
try {
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(90000);
RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
postMethod.setRequestHeader("sign", OAPropUtil.contract_synOTC_sign);
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
return null;
}
/**
* @param url 地址
* @param valuePairs 参数
* @return 返回的信息
* @throws Exception 异常信息
* @description post方法
* @author zhsong
* @create 2015年11月2日下午4:21:43
* @version 1.0
*/
public static String postToFF(String url, NameValuePair[] valuePairs) throws Exception {
HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.setRequestBody(valuePairs);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
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 postToXF(String url, NameValuePair[] valuePairs) throws Exception {
HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
PostMethod postMethod = new UTF8PostMethod(url);
postMethod.setRequestBody(valuePairs);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(35000);
byte[] b = JSON.toJSONString(valuePairs).getBytes("utf-8");
InputStream is = new ByteArrayInputStream(b, 0, b.length);
RequestEntity requestEntity = new InputStreamRequestEntity(is, b.length,
"text/xml; charset=utf-8");
postMethod.setRequestEntity(requestEntity);
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;
}
/**
* post请求携带请求头
*
* @param url 地址
* @param valuePairs 参数
* @param headerMap 请求头信息
* @return String
* @throws Exception
* @desc post 方式
* @author rfzhou3
* @date 2022-12-19
*/
public static String postWithHeader(String url, NameValuePair[] valuePairs, Map<String, String> headerMap) throws Exception {
HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
PostMethod postMethod = new OAUtil.UTF8PostMethod(url);
// 设置请求头信息
if (headerMap != null && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
postMethod.setRequestHeader(key, headerMap.get(key));
}
}
postMethod.setRequestBody(valuePairs);
HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
// 设置连接超时时间(单位毫秒)
managerParams.setConnectionTimeout(3000);
managerParams.setSoTimeout(10000);
try {
int statusCode = httpclient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
return postMethod.getResponseBodyAsString();
}
} catch (IOException e) {
e.printStackTrace();
throw new Exception("网络异常!");
} finally {
postMethod.releaseConnection();
}
return null;
}
public static NameValuePair[] convertMap2NameValuePairs(Map<String, String> data) {
Set<Map.Entry<String, String>> entrySet = data.entrySet();
int size = entrySet.size();
NameValuePair[] nameValuePairs = new NameValuePair[size];
List<NameValuePair> nameValuePairList = new ArrayList<>();
for (Map.Entry<String, String> entry : entrySet) {
String key = entry.getKey();
String value = entry.getValue();
NameValuePair nameValuePair = new NameValuePair(key, value);
nameValuePairList.add(nameValuePair);
}
for (int i = 0; i < nameValuePairList.size(); i++) {
nameValuePairs[i] = nameValuePairList.get(i);
}
return nameValuePairs;
}
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;
}
public static String postWithHeaderIgnoreSSL(String url, String json, 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));
}
}
post.setHeader("Content-type", "application/json;charset=utf-8");
try {
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
.setSocketTimeout(20000).setConnectTimeout(3000).build();
post.setConfig(requestConfig);
StringEntity s = new StringEntity(json,"UTF-8");
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/json");
//设置请求参数
post.setEntity(s);
HttpResponse response = httpclient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK){
//返回json格式
String res = EntityUtils.toString(response.getEntity(),"UTF-8");
post.releaseConnection();
return res;
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (post != null)
post.releaseConnection();
if (httpclient != null){
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String postIgnoreSSL(String url, String json, Map<String, String> headerMap) throws Exception {
HttpClientBuilder builder = HttpClients.custom();
builder.setSSLHostnameVerifier((hostName, sslSession) -> {
return true; // 证书校验通过
});
CloseableHttpClient httpclient = builder.build();
HttpPost post = new HttpPost(url);
// 设置请求头信息
if (headerMap != null && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
post.addHeader(key, headerMap.get(key));
}
}
post.setHeader("Content-type", "application/json;charset=utf-8");
try {
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
.setSocketTimeout(20000).setConnectTimeout(3000).build();
StringEntity s = new StringEntity(json,"UTF-8");
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/json");
//设置请求参数
post.setEntity(s);
HttpResponse response = httpclient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK){
//返回json格式
String res = EntityUtils.toString(response.getEntity(),"UTF-8");
post.releaseConnection();
return res;
} else {
System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (post != null)
post.releaseConnection();
if (httpclient != null){
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 创建模拟客户端(针对 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();
}
/**
* 跳过ssl验证 form表单提交
* @param url /
* @param param /
* @param headerMap /
* @return /
* @throws Exception /
*/
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;
}
}