接第三方接口需要封装http请求,调用第三方的数据接口,请求数据返回给前端。注:第三方接口出入参都是json格式。
1、请求controller:
@RequestMapping(value = "/getAirMsg")
public String getAirMsg(@RequestParam(value = "apiUrl")String apiUrl,
@RequestParam(value = "userId", required = false, defaultValue = "")Long userId,
@RequestParam(value = "content", required = false, defaultValue = "")String content,
HttpServletResponse response) throws Exception {
// 定义两个jsonObject
System.out.println("*****content,获得参数:*****"+content);
JSONObject jsonMax=new JSONObject();
if (content == null || content.equals("")) {
jsonMax.put("ApiKey", AirUtil.ApiKey);
jsonMax.put("Sign", AirUtil.Sign);
jsonMax.put("Timestamp", AirUtil.Timestamp);
}else {
//content = new String(content.getBytes("ISO-8859-1"), "UTF-8");
JSONObject jsonObj = JSONObject.fromObject(content);
jsonMax.put("ApiKey", AirUtil.ApiKey);
jsonMax.put("Sign", AirUtil.Sign);
jsonMax.put("Timestamp", AirUtil.Timestamp);
jsonMax.put("Data", jsonObj);
System.out.println("*****jsonMax,请求参数:*****"+jsonMax);
}
String result = HttpUtils.doPost(AirUtil.requsetUrl+apiUrl,jsonMax.toString());
JSONObject dataJson=JSONObject.fromObject(result);
String IsSuccess=dataJson.getString("IsSuccess");
// JSONObject data=dataJson.getJSONObject("Data");
System.out.println("****第三方返回结果*****"+result);
//创建订单
//申请订单
if (IsSuccess.equals("true")) {
if (apiUrl.equals("Flight/CreateOrder")) {
JSONObject data=dataJson.getJSONObject("Data");
String orderNo = data.getString("OrderNo");
// System.out.println("********"+orderNo+"***************");
AirOrderDto airOrderDto = new AirOrderDto();
airOrderDto.setUserId(userId);
airOrderDto.setAirOrderNo(orderNo);
airOrderDto.setCreateTime(new Date());
airOrderDto.setUpdateTime(new Date());
airOrderService.insertSelective(airOrderDto);
System.out.println("****成功信息*****"+result);
}
return result;
}
if (IsSuccess.equals("false")) {
System.out.println("****失败信息*****"+result);
return result;
}
return result;
}
2、封装http请求工具类:
package com.yaan.youqi.util;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import org.apache.commons.collections.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
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.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
public class HttpUtils {
private static final int TIMEOUT_IN_MILLIONS = 10000;
/**
* Get请求,获得返回数据
*
* @param urlStr
* @return
* @throws Exception
*/
public static String doGet(String url, Map<String, Object> params) {
String result = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
if (MapUtils.isNotEmpty(params)) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue()
.toString());
}
}
uriBuilder.setCharset(StandardCharsets.UTF_8);
HttpGet httpget = new HttpGet(uriBuilder.build());
httpget.setConfig(setRequestConfig());
response = httpclient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpclient);
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* @return 所代表远程资源的响应结果
* @throws Exception
*/
public static String doPost(String url, String params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
httpPost.setConfig(setRequestConfig());
// List<NameValuePair> pairList = new ArrayList<NameValuePair>();
// if (MapUtils.isNotEmpty(params)) {
// for (Map.Entry<String, Object> entry : params.entrySet()) {
// NameValuePair pair = new BasicNameValuePair(entry.getKey(),
// entry.getValue().toString());
// pairList.add(pair);
// }
// }
HttpEntity entity = EntityBuilder
.create()
.setText(params)
// .setParameters(pairList)
.setContentType(ContentType.APPLICATION_JSON).build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
httpStr = EntityUtils.toString(response.getEntity(),
StandardCharsets.UTF_8);
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* ssl的post同步請求
* @param url
* @param params
* @return
*/
public static String doPostSSL(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(createSSLConnectionManager())
.setDefaultRequestConfig(setRequestConfig()).build();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpPost.setConfig(setRequestConfig());
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
if (MapUtils.isNotEmpty(params)) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(),
entry.getValue().toString());
pairList.add(pair);
}
}
httpPost.setEntity(EntityBuilder
.create()
.setParameters(pairList)
.setContentType(
ContentType.create(URLEncodedUtils.CONTENT_TYPE,
MIME.UTF8_CHARSET)).build());
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consumeQuietly(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 发送 SSL GET 请求(HTTPS),K-V形式
*
* @param url
* API接口URL
* @param params
* 参数map
* @return
*/
public static String doGetSSL(String url, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(createSSLConnectionManager())
.setDefaultRequestConfig(setRequestConfig()).build();
HttpGet httpget = new HttpGet();
CloseableHttpResponse response = null;
String httpStr = null;
try {
httpget.setConfig(setRequestConfig());
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
if (MapUtils.isNotEmpty(params)) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(),
entry.getValue().toString());
pairList.add(pair);
}
}
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.setParameters(pairList);
uriBuilder.setCharset(StandardCharsets.UTF_8);
httpget.setURI(uriBuilder.build());
response = httpClient.execute(httpget);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 文件上传
* @param url
* @param fileMap
* @param params
* @return
*/
public static String httpUpload(String url, Map<String, byte[]> fileMap,
Map<String, String> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPut = new HttpPost(url);
CloseableHttpResponse response = null;
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
mBuilder.setLaxMode();
for (Map.Entry<String, String> entry : params.entrySet()) {
mBuilder.addTextBody(entry.getKey(), entry.getValue());
}
try {
httpPut.setConfig(setRequestConfig());
if (fileMap != null && fileMap.size() > 0) {
Iterator<Entry<String, byte[]>> fileIter = fileMap.entrySet()
.iterator();
while (fileIter.hasNext()) {
Map.Entry<String, byte[]> fileEntry = fileIter.next();
mBuilder.addBinaryBody(fileEntry.getKey(),
fileEntry.getValue());
}
}
httpPut.setEntity(mBuilder.build());
response = httpClient.execute(httpPut);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
*/
private static PoolingHttpClientConnectionManager createSSLConnectionManager() {
SSLContext sslcontext = null;
try {
sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new HostnameVerifier() {
@Override
public boolean verify(String paramString,
SSLSession paramSSLSession) {
return true;
}
});
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.register("http",
PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslsf).build();
// 设置连接池
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// Increase max total connection to 200
connMgr.setMaxTotal(100);
// Increase default max connection per route to 20
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
connMgr.setValidateAfterInactivity(TIMEOUT_IN_MILLIONS);
SocketConfig socketConfig = SocketConfig.custom()
.setSoTimeout(TIMEOUT_IN_MILLIONS).build();
connMgr.setDefaultSocketConfig(socketConfig);
return connMgr;
}
/**
* httpclient全局设置
*
* @return
*/
public static RequestConfig setRequestConfig() {
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(TIMEOUT_IN_MILLIONS);
// 设置读取超时
configBuilder.setSocketTimeout(TIMEOUT_IN_MILLIONS);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(TIMEOUT_IN_MILLIONS);
// 首先设置全局的标准cookie策略
configBuilder.setCookieSpec(CookieSpecs.STANDARD_STRICT);
return configBuilder.build();
}
}
3、要转json的实体类
public class AirParam<T> implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8460012563972749238L;
@JSONField(name = "ApiKey")
private String ApiKey;
@JSONField(name="Sign")
private String Sign;
@JSONField(name="Timestamp")
private String Timestamp;
@JSONField(name="Data")
private T Data;
public AirParam(String apiKey,String sign, String timestamp, T t){
this.ApiKey = apiKey;
this.Sign = sign;
this.Timestamp = timestamp;
this.Data = t;
}
public String getApiKey() {
return ApiKey;
}
public void setApiKey(String apiKey) {
ApiKey = apiKey;
}
public String getSign() {
return Sign;
}
public void setSign(String sign) {
Sign = sign;
}
public String getTimestamp() {
return Timestamp;
}
public void setTimestamp(String timestamp) {
Timestamp = timestamp;
}
public T getData() {
return Data;
}
public void setData(T data) {
this.Data = data;
}
}
转载于:https://my.oschina.net/u/3727427/blog/2990870