1.restTemplate方法
//body体中存入请求信息
Map paramsMap = new HashMap(8);
List stringlist=new ArrayList<>();
paramsMap.put("consumerCats", stringlist);//存入空数据
paramsMap.put("orderStatuss", myOrderListQuery.getOrderStatuss());
String msg=JSON.toJSONString(paramsMap);
//header请求头中存入信息
HttpHeaders headerMap = new HttpHeaders();
headerMap.add("token", myOrderListQuery.getUserId());
headerMap.add("content-type","application/json");
headerMap.add("content-charset","utf-8");
//请求信息存入paramEntity
HttpEntity paramEntity = new HttpEntity<>(msg, headerMap);
RestTemplate restTemplate =new RestTemplate();
ResponseEntity responseEntitys = restTemplate.exchange(url+"?userId="+query.getUserId(),
HttpMethod.POST, paramEntity, JSONObject.class);
//返回数据用JSONObject接收
JSONObject resultJson = responseEntitys.getBody();
需要引入import org.springframework.web.client.RestTemplate;
2.htticlient方法
String url= employeeMsg+"?memberNo="+carNum ;
String result = HttpClientUtil.post(url, "", "utf-8", 80000);
Map resultMap = JSON.parseObject(result, Map.class);
HttpClientUtil工具类代码如下:
package com.csair.mpms.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.csair.mpms.tool.MD5Utils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpClientUtil
{
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static int TIME_OUT_MILLISECOND = 10000;
/**
* 设置请求和传输超时时间
*/
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIME_OUT_MILLISECOND).setConnectTimeout(TIME_OUT_MILLISECOND).build();
public static void main(String[] args) throws Exception {
String reqURL = "http://10.108.25.229:8080/xxl-job-admin/jobinfo/add";
List sendData = new ArrayList();
//
// jobGroup: 1
// jobDesc: 远程接口测试任务
// executorRouteStrategy: FIRST
// jobCron: * */5 * * * ?
// glueType: BEAN
// executorHandler: demoJobHandler
// executorBlockStrategy: SERIAL_EXECUTION
// childJobId: 3
// executorTimeout: 30
// executorFailRetryCount: 1
// author: 李四
// alarmEmail: test@csair.com
// executorParam: 测试参数
// glueRemark: GLUE代码初始化
// glueSource:
//这个要可配置
sendData.add(new NameValuePair("jobGroup","1"));
//分群名
sendData.add(new NameValuePair("jobDesc","远程接口测试任务"));
//这个要可配置
sendData.add(new NameValuePair("executorRouteStrategy","FIRST"));
//分群的计划
sendData.add(new NameValuePair("jobCron","* */5 * * * ?"));
sendData.add(new NameValuePair("glueType","BEAN"));
//这个要可配置
sendData.add(new NameValuePair("executorHandler","demoJobHandler"));
sendData.add(new NameValuePair("executorBlockStrategy","DISCARD_LATER"));
//sendData.add(new NameValuePair("childJobId","3"));
sendData.add(new NameValuePair("executorTimeout","1800"));
//sendData.add(new NameValuePair("executorFailRetryCount","1"));
//当前用户名
sendData.add(new NameValuePair("author","李四11"));
//目前放空
sendData.add(new NameValuePair("alarmEmail","test@csair.com"));
//参数传分群ID
sendData.add(new NameValuePair("executorParam","测试参数"));
//分群 名字或备注
sendData.add(new NameValuePair("glueRemark","GLUE代码初始化"));
sendData.add(new NameValuePair("glueSource",""));
post(reqURL, sendData, "UTF-8", TIME_OUT_MILLISECOND);
}
/**
* 发送 Post请求
* @param url
* @param params
* @param decodeCharset
* @return
*/
public static String post(String url, List params, String decodeCharset) {
return post(url, params, decodeCharset , TIME_OUT_MILLISECOND);
}
public static String post(String url, List params, String decodeCharset , int timeout, List headers) {
HttpClient httpClient = new HttpClient(); // 创建默认的httpClient实例
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = (NameValuePair[]) params.toArray(new NameValuePair[params.size()]);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
httpClient.getParams().setContentCharset(decodeCharset);
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
if (null != headers){
for (Header header:headers){
postMethod.setRequestHeader(header);
}
}
// 执行postMethod
int statusCode = 0;
String responseContent = "";
try {
statusCode = httpClient.executeMethod(postMethod);
if (statusCode == 200) {
responseContent = postMethod.getResponseBodyAsString();
} else {
responseContent = String.valueOf(statusCode);
}
} catch (Exception e) {
logger.error("HttpClient-post请求异常", e);
}
return responseContent;
}
/**
* 发送 Post请求
* @param url
* @param params
* @param decodeCharset
* @param timeout
* @return
*/
public static String post(String url, List params, String decodeCharset , int timeout) {
HttpClient httpClient = new HttpClient(); // 创建默认的httpClient实例
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = (NameValuePair[]) params.toArray(new NameValuePair[params.size()]);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
httpClient.getParams().setContentCharset(decodeCharset);
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = 0;
String responseContent = "";
try {
statusCode = httpClient.executeMethod(postMethod);
if (statusCode == 200) {
responseContent = postMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
return responseContent;
}
public static String post(String url, String params, String decodeCharset , int timeout) {
HttpClient httpClient = new HttpClient(); // 创建默认的httpClient实例
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
httpClient.getParams().setContentCharset(decodeCharset);
// 将表单的值放入postMethod中
postMethod.setRequestBody(params);
Header header=new Header("content-type","application/json");
postMethod.setRequestHeader(header);
int statusCode = 0;
String responseContent = "";
try {
statusCode = httpClient.executeMethod(postMethod);
if (statusCode == 200) {
responseContent = postMethod.getResponseBodyAsString();
}
} catch (Exception e) {
logger.info("调用接口失败 --{}--",e);
}
return responseContent;
}
public static String get(String url)
throws Exception {
GetMethod m = new GetMethod(url);
StringBuilder rsp = new StringBuilder();
HttpClient httpClient = null;
try {
m.setRequestHeader("Connection", "close");
httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(10000);
httpClient.getHttpConnectionManager().getParams()
.setSoTimeout(10000);
if (httpClient.executeMethod(m) == HttpStatus.SC_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
m.getResponseBodyAsStream(), "utf-8"));
boolean first = true;
String line;
try {
while ((line = br.readLine()) != null) {
if (first) {
first = false;
} else {
rsp.append('\n');
}
rsp.append(line);
}
} catch (Exception e) {
throw e;
} finally {
try {
br.close();
} catch (Exception e) {
}
}
return rsp.toString();
} else {
return null;
}
} catch (Exception e) {
throw e;
} finally {
try {
m.releaseConnection();
SimpleHttpConnectionManager simpleHttpConnectionManager = (SimpleHttpConnectionManager) httpClient
.getHttpConnectionManager();
if (simpleHttpConnectionManager != null) {
simpleHttpConnectionManager.shutdown();
}
} catch (Exception e) {
}
}
}
/**
*
* @param url
* @param params
* @param decodeCharset
* @param timeout
* @param header1
* @param header2
* @param header3
* @return
*/
public static String cbdCabinPost(String url, String params, String decodeCharset , int timeout,String header1,String header2,String header3) {
HttpClient httpClient = new HttpClient(); // 创建默认的httpClient实例
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
httpClient.getParams().setContentCharset(decodeCharset);
// 将表单的值放入postMethod中
postMethod.setRequestBody(params);
String encrypt = MD5Utils.encrypt(header1 + header2 + header3);
Header header=new Header("content-type","application/json");
Header headerOne = new Header("username",header1);
Header headerTwo = new Header("encryptPwd",encrypt);
Header headerThree = new Header("timestamp",header3);
postMethod.setRequestHeader(header);
postMethod.setRequestHeader(headerOne);
postMethod.setRequestHeader(headerTwo);
postMethod.setRequestHeader(headerThree);
int statusCode = 0;
String responseContent = "";
try {
statusCode = httpClient.executeMethod(postMethod);
if (statusCode == 200) {
responseContent = postMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
return responseContent;
}
public static String cbdCabinGet(String url,String header1,String header2,String header3)
throws Exception {
GetMethod m = new GetMethod(url);
StringBuilder rsp = new StringBuilder();
HttpClient httpClient = null;
String encrypt = MD5Utils.encrypt(header1 + header2 + header3);
try {
m.setRequestHeader("Connection", "close");
m.setRequestHeader("username",header1);
m.setRequestHeader("encryptPwd",encrypt);
m.setRequestHeader("timestamp",header3);
httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(10000);
httpClient.getHttpConnectionManager().getParams()
.setSoTimeout(10000);
if (httpClient.executeMethod(m) == HttpStatus.SC_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
m.getResponseBodyAsStream(), "utf-8"));
boolean first = true;
String line;
try {
while ((line = br.readLine()) != null) {
if (first) {
first = false;
} else {
rsp.append('\n');
}
rsp.append(line);
}
} catch (Exception e) {
throw e;
} finally {
try {
br.close();
} catch (Exception e) {
}
}
return rsp.toString();
} else {
return null;
}
} catch (Exception e) {
throw e;
} finally {
try {
m.releaseConnection();
SimpleHttpConnectionManager simpleHttpConnectionManager = (SimpleHttpConnectionManager) httpClient
.getHttpConnectionManager();
if (simpleHttpConnectionManager != null) {
simpleHttpConnectionManager.shutdown();
}
} catch (Exception e) {
}
}
}
public static String post(String url, String params, String decodeCharset , int timeout,List headerList) {
HttpClient httpClient = new HttpClient(); // 创建默认的httpClient实例
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
httpClient.getParams().setContentCharset(decodeCharset);
// 将表单的值放入postMethod中
postMethod.setRequestBody(params);
if(headerList!=null && headerList.size() > 0){
for (Header header : headerList) {
postMethod.setRequestHeader(header);
}
}
int statusCode = 0;
String responseContent = "";
try {
statusCode = httpClient.executeMethod(postMethod);
if (statusCode == 200) {
responseContent = postMethod.getResponseBodyAsString();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
}
return responseContent;
}
public static String doGet(String url , int timeout, List headers)
throws Exception {
GetMethod m = new GetMethod(url);
StringBuilder rsp = new StringBuilder();
HttpClient httpClient = null;
try {
if (headers!=null && !headers.isEmpty()){
for (Header header: headers){
m.setRequestHeader(header);
}
}
httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams()
.setConnectionTimeout(timeout);
httpClient.getHttpConnectionManager().getParams()
.setSoTimeout(timeout);
if (httpClient.executeMethod(m) == HttpStatus.SC_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
m.getResponseBodyAsStream(), "utf-8"));
boolean first = true;
String line;
try {
while ((line = br.readLine()) != null) {
if (first) {
first = false;
} else {
rsp.append('\n');
}
rsp.append(line);
}
} catch (Exception e) {
throw e;
} finally {
try {
br.close();
} catch (Exception e) {
}
}
return rsp.toString();
} else {
return null;
}
} catch (Exception e) {
throw e;
} finally {
try {
m.releaseConnection();
SimpleHttpConnectionManager simpleHttpConnectionManager = (SimpleHttpConnectionManager) httpClient
.getHttpConnectionManager();
if (simpleHttpConnectionManager != null) {
simpleHttpConnectionManager.shutdown();
}
} catch (Exception e) {
}
}
}
/**
* 构建ssl请求
* @param httpUrl
* @param params
* @param headers
* @return
*/
public static String postSSL(String httpUrl, Map params, Map headers) {
String result = null ;
CloseableHttpClient httpclient = createSSLClientDefault();
ResponseHandler responseHandler = new BasicResponseHandler();
HttpPost httpPost = new HttpPost(httpUrl);
httpPost.setConfig(requestConfig);
httpPost.setHeader("Connection", "close");
httpPost.setHeader("Content-Type","application/json");
if (headers!=null && headers.size()>0){
for (Map.Entry entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpPost.setHeader(key, value);
}
}
//将参数转成json字符串并设置json的编码UTF-8
StringEntity se = new StringEntity(JSONObject.toJSONString(params), ContentType.APPLICATION_JSON);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
String response = null;
try {
response = httpclient.execute(httpPost, responseHandler);
JSONObject ret = JSONObject.parseObject(response);
result = ret.toJSONString();
} catch (IOException e) {
logger.error("postSSL异常", e);
} finally {
try {
httpclient.close();
} catch (IOException e) {
logger.error("httpclient.close() Exception", e);
}
}
return result;
}
public static CloseableHttpClient createSSLClientDefault(){
try {
//SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 在JSSE中,证书信任管理器类就是实现了接口X509TrustManager的类。我们可以自己实现该接口,让它信任我们指定的证书。
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
//信任所有
X509TrustManager x509mgr = new X509TrustManager() {
// 该方法检查客户端的证书,若不信任该证书则抛出异常
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
// 该方法检查服务端的证书,若不信任该证书则抛出异常
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
// 返回受信任的X509证书数组。
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { x509mgr }, null);
创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// HttpsURLConnection对象就可以正常连接HTTPS了,无论其证书是否经权威机构的验证,只要实现了接口X509TrustManager的类 MyX509TrustManager 信任该证书。
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 创建默认的httpClient实例.
return HttpClients.createDefault();
}
}