需要的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.qingtui.springbootdemo.utill;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpClientUtils {
public static JSONObject Get(String path, Map<String, Object> queryParams) throws IOException {
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);
JSONObject jsonObject = JSONObject.fromObject(result);
return jsonObject;
}
public static JSONObject Post(String path, String token, String open_id)
throws IOException {
CloseableHttpClient httpClient=null;
try {
String urlPath = path + "?access_token=" + token;
httpClient= HttpClients.createDefault();
HttpPost httpPost=new HttpPost(urlPath);
//添加传入参数
List<NameValuePair> pair=new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("open_id", open_id));
UrlEncodedFormEntity entity= new UrlEncodedFormEntity (pair,"utf-8");
httpPost.setEntity(entity);
//发送相应数据
CloseableHttpResponse reseponse=httpClient.execute(httpPost);
HttpEntity res=reseponse.getEntity();
BufferedReader reader=new BufferedReader(new InputStreamReader(res.getContent(),"UTF-8"));
String result="";
String line;
while((line=reader.readLine()) != null){
result+=line;
}
JSONObject jsonObject = JSONObject.fromObject(result);
return jsonObject;
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
类二:
package im.qingtui.springbootdemo.utill;
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;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
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)
throws java.security.cert.CertificateException {
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 (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
}
}