1、创建工具类 HttpClient
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpStatus;
import org.apache.fig.RequestConfig;
import org.apache.hods.*;
import org.apache.http.client.utils.URIBuilder;
import org.ity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;public class HttpClient {// 编码格式。发送编码格式统一用UTF-8private static final String ENCODING = "UTF-8";// 设置连接超时时间,单位毫秒。private static final int CONNECT_TIMEOUT = 100000;// 请求获取数据的超时时间(即响应时间),单位毫秒。private static final int SOCKET_TIMEOUT = 100000;/*** 发送post请求;带请求头和请求参数** @param url 请求地址* @param data 请求参数集合* @return* @throws Exception*/public static HttpClientResult doPost(String url, Map<String, Object> data) throws Exception {// 创建httpClient对象-https地址CloseableHttpClient httpClient = new SSLClient();// 创建http对象HttpPost httpPost = new HttpPost(url);/*** setConnectTimeout:设置连接超时时间,单位毫秒。* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。*/RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();httpPost.setConfig(requestConfig);httpPost.addHeader("Content-type", "application/json; charset=utf-8");httpPost.setHeader("Accept", "application/json");// 设置请求参数httpPost.setEntity(new JSONString(data), Charset.forName("utf-8")));// 创建httpResponse对象CloseableHttpResponse httpResponse = null;try {// 执行请求并获得响应结果return getHttpClientResult(httpResponse, httpClient, httpPost);} finally {// 释放资源release(httpResponse, httpClient);}}/*** 发送get请求;带请求参数** @param url 请求地址* @param data 参数集合* @return 返回结果*/public static HttpClientResult doGet(String url, Map<String, Object> data) throws Exception {// 创建httpClient对象-https地址CloseableHttpClient httpClient = new SSLClient();// 创建访问的地址URIBuilder uriBuilder = new URIBuilder(url);if (data != null) {Set<Map.Entry<String, Object>> entrySet = Set();for (Map.Entry<String, Object> entry : entrySet) {uriBuilder.Key(), String.Value()));}}HttpGet httpGet = new HttpGet(uriBuilder.build());RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();httpGet.setConfig(requestConfig);httpGet.addHeader("Content-type", "application/json; charset=utf-8");httpGet.setHeader("Accept", "application/json");// 创建httpResponse对象CloseableHttpResponse httpResponse = null;try {return getHttpClientResult(httpResponse, httpClient, httpGet);} finally {release(httpResponse, httpClient);}}/*** Description: 获得响应结果** @param httpResponse* @param httpClient* @param httpMethod* @return* @throws Exception*/public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {// 执行请求httpResponse = ute(httpMethod);// 获取返回结果if (httpResponse != null && StatusLine() != null) {String content = "";if (Entity() != null) {content = Entity(), ENCODING);}return new StatusLine().getStatusCode(), content);}return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);}/*** Description: 释放资源** @param httpResponse 返回* @param httpClient 请求*/public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {// 释放资源if (httpResponse != null) {httpResponse.close();}if (httpClient != null) {httpClient.close();}}}
2、创建返回数据格式封装类
import lombok.Data;import java.io.Serializable;/*** @author 詹浩* @date 2020/2/11 0011*/
@Data
public class HttpClientResult implements Serializable {/*** 响应状态码*/private int code;/*** 响应数据*/private String content;public HttpClientResult(int code) {de = code;}public HttpClientResult(int code, String content) {de = t = content;}
}
3、创建 SSLClient 类
import org.ClientConnectionManager;
import org.scheme.Scheme;
import org.scheme.SchemeRegistry;
import org.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;
import CertificateException;
import X509Certificate;public class SSLClient extends DefaultHttpClient {public SSLClient() throws Exception {super();SSLContext ctx = Instance("TLS");X509TrustManager tm = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};ctx.init(null, new TrustManager[]{tm}, null);SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm = ConnectionManager();SchemeRegistry sr = SchemeRegistry();sr.register(new Scheme("https", 443, ssf));}}
4、所需的maven依赖
<!--org.apache.http的依赖开始--> <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version> </dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.5</version> </dependency> <!--org.apache.http的依赖结束-->
本文发布于:2024-02-02 03:31:25,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170681690141093.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |