java里面封装https请求工具类2

作者 : admin 本文共11061个字,预计阅读时间需要28分钟 发布时间: 2024-06-10 共2人阅读

其他写法
http://blog.csdn.net/weixin_44372802/article/details/132620809?spm=1001.2014.3001.5501

encodeJson 是请求参数的密文格式(大公司都是要对请求参数加密的)

ResponseBean 是自己或者对方定义的返回内容参数

public ResponseBean sendByEncodeJson(String encodeJson, String interfaceName) throws IOException {
        //构建完整url
        Map<String, String>  urlMap = buildUrl(interfaceName);
        String url = JpHttpUtils.initUrl(sfUrl, urlMap);
        log.info("请求地址" + url+"请求报文" + encodeJson);
        String responseString = JpHttpUtils.post(url, encodeJson);
        log.info("远程接口响应:" + responseString);
        //JSON 字符串转换为 SfResponseBean 对象
        return new Gson().fromJson(responseString, SfResponseBean.class);
    }
public Map<String, String> buildUrl(String method) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("appId",appId);
        map.put("source",source);
        map.put("appToken",appToken);
        map.put("userToken",userToken);
        map.put("method",method);
        map.put("timestamp",String.valueOf(System.currentTimeMillis()));
        map.put("v","1.0");
        return map;
    }
@Slf4j
public class JpHttpUtils {
private static final Logger logger = LoggerFactory.getLogger(JpHttpUtils.class);
private static final int SOCKET_TIMEOUT = 30000;// 请求超时时间
private static final int CONNECT_TIMEOUT = 30000;// 传输超时时间
/**
* 发送xml请求到server端
*
* @param url       xml请求数据地址
* @param xmlString 发送的xml数据流
* @return null发送失败,否则返回响应内容
*/
public static String sendPost(String url, String xmlString) {
StringBuilder retStr = new StringBuilder();
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
//  设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).build();
httpPost.setConfig(requestConfig);
try {
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
StringEntity data = new StringEntity(xmlString, StandardCharsets.UTF_8);
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// 打印响应内容
retStr.append(EntityUtils.toString(entity, "UTF-8"));
logger.info("response:{}", retStr);
}
} catch (Exception e) {
logger.error("exception in doPostSoap1_1", e);
} finally {
// 释放资源
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return retStr.toString();
}
public static String sendPostByForm(String url, Map<String,String> formMap) {
List<NameValuePair> params=new ArrayList<NameValuePair>();
for(Map.Entry<String, String> entry : formMap.entrySet()){
params.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
HttpResponse response = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
HttpClient httpClient =HttpClientBuilder.create().build();
response = httpClient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = response.getEntity();
String result = null;
try {
result = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("sendPostByForm response:"+result);
return result;
}
public static String sendPut(String url, String string, Map<String,String> headerMap) {
StringBuilder retStr = new StringBuilder();
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
//  设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT).build();
httpPost.setConfig(requestConfig);
try {
httpPost.setHeader("Content-Type", "application/json");
if(string!=null){
StringEntity data = new StringEntity(string, StandardCharsets.UTF_8);
httpPost.setEntity(data);
}
if (headerMap != null) {
for (String key : headerMap.keySet()) {
httpPost.setHeader(new BasicHeader(key, headerMap.get(key)));
}
}
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// 打印响应内容
retStr.append(EntityUtils.toString(entity, "UTF-8"));
logger.info("response:{}", retStr);
}
} catch (Exception e) {
logger.error("exception in doPostSoap1_1", e);
} finally {
// 释放资源
try {
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return retStr.toString();
}
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
/**
* 带header参数
* @param url
* @param param
* @return
*/
public static String doGetSetHeader(String url, Map<String, String> param,Map<String, String> headerMap) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
// 设置请求的参数
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 设置 Header
if (headerMap != null) {
for (String key : headerMap.keySet()) {
httpGet.setHeader(key, headerMap.get(key));
}
}
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(null != response){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(null != response){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostJson(String url, String json,Map<String,String> headers)  {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
for(String  key:headers.keySet()){
httpPost.setHeader(key,headers.get(key));
}
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
log.error("Exception",e);
} finally {
try {
if(null != response){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 创建一个SSL信任所有证书的httpClient对象
*
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
//连接符
public static final String SPE3_CONNECT = "&";
//赋值符
public static final String SPE4_EQUAL = "=";
//问号符
public static final String SPE5_QUESTION = "?";
public static final String SPE1_COMMA = ",";
//示意符
public static final String SPE2_COLON = ":";
public static final String ENCODING = "UTF-8";
public static String initUrl(String host, Map<String, String> queries) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (null != queries) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : queries.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append(SPE3_CONNECT);
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(String.valueOf(query.getValue()))) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(String.valueOf(query.getValue()))) {
sbQuery.append(SPE4_EQUAL);
sbQuery.append(URLEncoder.encode(String.valueOf(query.getValue()), ENCODING));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append(SPE5_QUESTION).append(sbQuery);
}
}
return sbUrl.toString();
}
public static final int TIMEOUT = 30000;
/**
* HTTP -> POST
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static String post(String url, String param) {
String result = null;
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
try {
httpclient = HttpClients.createDefault();
HttpPost postmethod = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT)
.build();
postmethod.setConfig(requestConfig);
postmethod.addHeader("content-type", "application/json");
postmethod.setEntity(new StringEntity(param, "UTF-8"));
response = httpclient.execute(postmethod);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
}
} catch (Exception e) {
log.error("post请求异常", e);
} finally {
try {
httpclient.close();
} catch (IOException e) {
log.error("IOException post请求异常", e);
}
}
return result;
}
}
package com.bbyb.transportmonitor.utils.sf;
import lombok.Data;
import java.io.Serializable;
/**
*  请求实体
* @date 2024/5/31 10:02
*/
@Data
public class SfResponseBean implements Serializable {
/**
* 接口状态 200 成功 其它异常
*/
private String code;
private String message;
private boolean success;
private Model model;
private String data;
@Data
class Model  implements Serializable {
private String erpOrder;
private String code;
private String sfOrderNo;
}
}
本站无任何商业行为
个人在线分享 » java里面封装https请求工具类2
E-->