需要的jar包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
类一:
package im.qiaofeng.file.fileuploaddownload.utils;
import com.alibaba.fastjson.JSONObject;
import im.qiaofeng.file.fileuploaddownload.constants.ErrorCodeConstants;
import im.qiaofeng.file.fileuploaddownload.exception.UtilException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
@Slf4j
public class HttpClientUtil {
public static JSONObject Get(String path, Map<String, Object> queryParams) {
try {
HttpClient httpclient = HttpClientMng.getClient();
Iterator<String> iter = queryParams.keySet().iterator();
String temp = path + "?";
while (iter.hasNext()) {
String key = iter.next();
temp = temp + key + "=" + queryParams.get(key) + "&";
}
String url = temp.substring(0, temp.lastIndexOf("&"));
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
return JSONObject.parseObject(result);
} catch (IOException e) {
log.error("发送get请求失败:" + e);
throw new UtilException(ErrorCodeConstants.SYSTEM_ERROR);
}
}
public static JSONObject post(String path, String jsonStr) {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(path);
//添加传入参数
httpPost.setEntity(new StringEntity(jsonStr, StandardCharsets.UTF_8));
//发送相应数据
CloseableHttpResponse reseponse = httpClient.execute(httpPost);
HttpEntity res = reseponse.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(res.getContent(), StandardCharsets.UTF_8));
String result = "";
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
return JSONObject.parseObject(result);
} catch (Exception e) {
log.error("发送post请求失败:" + e);
/**
*这里是自定义的错误类,自己用时记得自定义
**/
throw new UtilException(ErrorCodeConstants.SYSTEM_ERROR);
}
}
}
类二:
package im.qiaofeng.file.fileuploaddownload.utils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
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.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
@Slf4j
public class HttpClientMng {
private static HttpClient client = null;
public static HttpClient getClient() {
getTrustedHttpClient();
return client;
}
@SuppressWarnings("deprecation")
private static synchronized void getTrustedHttpClient() {
try {
if (client == null) {
HttpClientBuilder b = HttpClientBuilder.create();
// 策略:允许加载所有证书
SSLContext sslContext = null;
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
return true;
}
}).build();
b.setSslcontext(sslContext);
// 不检测主机名
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
// 创建SSLSocketFactory来加载配置
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory).build();
// 创建connection-manager,配置Registry。支持多线程的使用
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
b.setConnectionManager(connMgr);
// 构建HttpClient
client = b.build();
}
} catch (Exception e) {
log.error("获取httpClient对象失败" + e);
}
}
}