创建一个service,参数就是url地址和JSONObject类型的参数
import com.alibaba.fastjson.JSONObject;
import com.sjq.ntnbzhfk.util.HttpClientUtilJJ;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service("portService")
public class PortService {
public JSONObject sendPostForm(String url,Map<String, Object> reqObj,String type) {
//type
// 1接收用@requestbody
// 2接收用@requestparam或者httpservletrequest.getParameter
try {
HttpClientUtilJJ http = new HttpClientUtilJJ();
String str = http.sendPostMap(url, reqObj, type);
return JSONObject.parseObject(str);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public JSONObject sendGetForm(String url,Map<String, Object> reqObj) {
try {
HttpClientUtilJJ http = new HttpClientUtilJJ();
String str = http.sendGetMap(url, reqObj);
return JSONObject.parseObject(str);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
具体实现:
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.io.IOException;
import java.util.*;
public class HttpClientUtil {
private int connectionRequestTimeout = 10000;
private int connectTimeout = 10000;
private int socketTimeout = 10000;
private String urlHead="";//接口头部
//这边是创建https请求的,http不需要
public CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
//post
public String sendPostMap(String postUrl, Map<String, Object> params,String type) throws Exception {
//type
// 1接收用@responsebody
// 2接收用@requestparam或者httpservletrequest.getParameter
CloseableHttpClient httpClient = createSSLClientDefault();//https
//CloseableHttpClient httpClient = HttpClients.createDefault();//http
try {
//实例化post方法
HttpPost httpost = new HttpPost(urlHead+postUrl);
config(httpost);
//提交参数
if("1".equals(type)){
String ms = String.valueOf(params);
StringEntity stringEntity = new StringEntity(String.valueOf(params),"UTF-8");
stringEntity.setContentType("application/json");
//将参数给post方法
httpost.setEntity(stringEntity);
}else{
List<NameValuePair> nvps = new ArrayList<>();
if(params != null){
Set<String> keySet = params.keySet();
for(String key:keySet){
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps,"UTF-8");
uefEntity.setContentType("application/x-www-form-urlencoded");
//将参数给post方法
httpost.setEntity(uefEntity);
}
//执行post方法
CloseableHttpResponse response = httpClient.execute(httpost, HttpClientContext.create());
//获取返回值
HttpEntity entity = response.getEntity();
String reponseStr = EntityUtils.toString(entity, "utf-8");
return reponseStr;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//get
public String sendGetMap(String postUrl, Map<String, Object> params) throws Exception
{
CloseableHttpClient httpClient = createSSLClientDefault();
try {
//提交参数
List<NameValuePair> nvps = new ArrayList<>();
if(params != null){
Set<String> keySet = params.keySet();
for(String key:keySet){
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
}
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps,"UTF-8");
uefEntity.setContentType("application/x-www-form-urlencoded");
//将参数给get方法
String sparam = EntityUtils.toString(uefEntity);
//实例化get方法
HttpGet httget = new HttpGet(urlHead+postUrl+"?"+sparam);
config(httget);
//执行get方法
CloseableHttpResponse response = httpClient.execute(httget);
//获取返回值
HttpEntity entity = response.getEntity();
String reponseStr = EntityUtils.toString(entity, "utf-8");
return reponseStr;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* @param httpRequestBase
*/
private void config(HttpRequestBase httpRequestBase) {
httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
httpRequestBase.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5");
httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
httpRequestBase.setHeader("connection", "Keep-Alive");
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build();
httpRequestBase.setConfig(requestConfig);
}
}
具体调用:
String url = "**";//去除头部的访问地址
JSONObject obj = new JSONObject();
param.put("**",**); //访问接口的参数
String type="1";//根据访问的接口写法确定1或2
// 1接收用@requestbody
// 2接收用@requestparam或者httpservletrequest.getParameter
JSONObject ret = portService.sendPostForm(url,param,type);
JSONObject ret = portService.sendGetForm(url,param);