如何让HttpClient同时支持http和https请求呢?
下文笔者通过示例的方式讲述使用HttpClient编写同时支持Http和Https请求的方法分享,如下所示
HttpClient简介
HttpClient: Apache Jakarta Common下的子项目 HttpClient的功能:为java项目提供功能丰富高效的http协议请求的SDK HttpClient的功能:类似模拟浏览器的各种行为,并接收浏览器返回的信息 用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包。HTTP Client和浏览器有点像,都可以用来发送请求,接收服务端响应的数据。但它不是浏览器,没有用户界面。HttpClient是一个客户端的http通信实现库,这个类库的作用是接收和发送http报文,使用这个类库,它相比传统的 。
HttpClient比HttpURLConnection 更加容易使用, 只需使用API即可传输和接收http协议返回的报文信息
HttpClient不同版本发送请求的方式
httpclient4.3以上使用CloseableHttpClient httpClient = HttpClients.createDefault(); httpclient4.x到httpclient4.3以下使用HttpClient client = new DefaultHttpClient(); httpclient3.x使用HttpClient client = new HttpClient();
httpclient3.x版本
HttpClient client = new HttpClient();
// 设置代理服务器地址和端口
// client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
// 使用 GET 方法 ,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 https
HttpMethodmethod = new GetMethod("http://java265.com/test");
// 使用POST方法
// HttpMethod method = new PostMethod("http://java265.com/test");
client.executeMethod(method);
// 输出服务器返回的状态
log.info(method.getStatusLine());
// 输出返回的信息
log.info(method.getResponseBodyAsString());
// 释放连接
method.releaseConnection();
httpclient4.x到httpclient4.3以下
public void get(String url, String encoding) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, encoding));
System.out.println(reader.readLine());
} catch (Exception e) {
e.printStackTrace();
} finally {
instream.close();
}
}
// 关闭连接.
client.getConnectionManager().shutdown();
}
httpclient4.3以上
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public static String get(String urlStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
// HTTP Get请求
HttpGet httpGet = new HttpGet(urlStr);
// 设置请求和传输超时时间
// RequestConfig requestConfig =
// RequestConfig.custom().setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).build();
// httpGet.setConfig(requestConfig);
String result = "";
try {
// 执行请求
HttpResponse getAddrResp = httpClient.execute(httpGet);
HttpEntity entity = getAddrResp.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
log.info("响应" + getAddrResp.getStatusLine());
} catch (Exception e) {
log.error(e.getMessage(), e);
return result;
} finally {
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
return result;
}
}
return result;
}
使用HttpClient-4.5.5版本
在pom.xml增加以下配置
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
新建HttpClient封装类,封装get,put,delete,post请求
package com.java265.util; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Arraylist; import java.util.Iterator; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; 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.LayeredConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Component; import javax.net.ssl.SSLContext; /** * @describe HttpClient同时支持发送http及htpps请求 */ @Component @Slf4j public class HttpClientUtils { private static int SocketTimeout = 5000;//5秒 private static int ConnectTimeout = 5000;//5秒 private static Boolean SetTimeOut = true; private static CloseableHttpClient getHttpClient() { RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create(); ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory(); registryBuilder.register("http", plainSF); //指定信任密钥存储对象和连接套接字工厂 try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); //信任任何链接 TrustStrategy anyTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build(); LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registryBuilder.register("https", sslSF); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } Registry<ConnectionSocketFactory> registry = registryBuilder.build(); //设置连接管理器 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); // connManager.setDefaultConnectionConfig(connConfig); // connManager.setDefaultSocketConfig(socketConfig); //构建客户端 return HttpClientBuilder.create().setConnectionManager(connManager).build(); } /** * @param url 请求的url * @describe get * @param queries 请求的参数,在url?后面的数据,可以传null * @return * @throws IOException */ public static String get(String url,Map<String, String> queries) throws IOException { log.info("get请求……"); String responseBody = ""; //CloseableHttpClient httpClient=HttpClients.createDefault(); //支持http及https请求 CloseableHttpClient httpClient = getHttpClient(); StringBuilder sb = new StringBuilder(url); if (queries != null && queries.keySet().size() > 0) { boolean firstFlag = true; Iterator iterator = queries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry<String, String>) iterator.next(); if (firstFlag) { sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue()); firstFlag = false; } else { sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue()); } } } HttpGet httpGet = new HttpGet(sb.toString()); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间 httpGet.setConfig(requestConfig); } try { log.info("正在执行请求是: " + httpGet.getRequestLine()); //请求数据 CloseableHttpResponse response = httpClient.execute(httpGet); System.out.println(response.getStatusLine()); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); responseBody = EntityUtils.toString(entity); } else { log.info("http返回错误状态:" + status); throw new ClientProtocolException("未知响应状态: " + status); } } catch (Exception ex) { ex.printStackTrace(); } finally { httpClient.close(); } return responseBody; } /** * @param url 请求的url * @describe put * @param queries 请求的参数,在url?后面的数据,可以传null * @return * @throws IOException */ public static String put(String url,Map<String, String> queries) throws IOException { log.info("put请求……"); String responseBody = ""; //CloseableHttpClient httpClient=HttpClients.createDefault(); //支持http及https请求 CloseableHttpClient httpClient = getHttpClient(); StringBuilder sb = new StringBuilder(url); if (queries != null && queries.keySet().size() > 0) { boolean firstFlag = true; Iterator iterator = queries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry<String, String>) iterator.next(); if (firstFlag) { sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue()); firstFlag = false; } else { sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue()); } } } HttpPut httpPut = new HttpPut(sb.toString()); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间 httpPut.setConfig(requestConfig); } try { log.info("正在执行请求是:" + httpPut.getRequestLine()); //请求数据 CloseableHttpResponse response = httpClient.execute(httpPut); System.out.println(response.getStatusLine()); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); responseBody = EntityUtils.toString(entity); } else { log.info("http返回错误状态:" + status); throw new ClientProtocolException("未知响应状态: " + status); } } catch (Exception ex) { ex.printStackTrace(); } finally { httpClient.close(); } return responseBody; } /** * @param url 请求的url * @describe delete * @param queries 请求的参数,在url?后面的数据,可以传null * @return * @throws IOException */ public static String delete(String url,Map<String, String> queries) throws IOException { log.info("delete请求……"); String responseBody = ""; //CloseableHttpClient httpClient=HttpClients.createDefault(); //支持http及https请求 CloseableHttpClient httpClient = getHttpClient(); StringBuilder sb = new StringBuilder(url); if (queries != null && queries.keySet().size() > 0) { boolean firstFlag = true; Iterator iterator = queries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry<String, String>) iterator.next(); if (firstFlag) { sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue()); firstFlag = false; } else { sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue()); } } } HttpDelete httpDelete = new HttpDelete(sb.toString()); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间 httpDelete.setConfig(requestConfig); } try { log.info("正在执行请求是:" + httpDelete.getRequestLine()); //请求数据 CloseableHttpResponse response = httpClient.execute(httpDelete); System.out.println(response.getStatusLine()); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); responseBody = EntityUtils.toString(entity); } else { log.info("http返回错误状态:" + status); throw new ClientProtocolException("未知响应状态: " + status); } } catch (Exception ex) { ex.printStackTrace(); } finally { httpClient.close(); } return responseBody; } /** * @param url 请求的url * @describe post * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null * @param params post form 提交的参数 * @return * @throws IOException */ public static String post(String url, Map<String, String> queries, Map<String, String> params) throws IOException { log.info("post请求……"); String responseBody = ""; //CloseableHttpClient httpClient = HttpClients.createDefault(); //支持https CloseableHttpClient httpClient = getHttpClient(); StringBuilder sb = new StringBuilder(url); if (queries != null && queries.keySet().size() > 0) { boolean firstFlag = true; Iterator iterator = queries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry<String, String>) iterator.next(); if (firstFlag) { sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue()); firstFlag = false; } else { sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue()); } } } HttpPost httpPost = new HttpPost(sb.toString()); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();//设置超时时间 httpPost.setConfig(requestConfig); } //添加参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (params != null && params.keySet().size() > 0) { Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next(); nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue())); } } httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); //请求数据 CloseableHttpResponse response = httpClient.execute(httpPost); try { System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); responseBody = EntityUtils.toString(entity); } else { log.info("http返回错误状态:" + response.getStatusLine().getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } finally { response.close(); } return responseBody; } }
调用验证
package com.java265.controller;
import com.java265.HttpClientUtils;
import com.java265.httpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RestController
@Slf4j
public class test {
@Autowired
public httpRequestUtil httpRequestUtil;
@Autowired
private HttpClientUtils httpClientUtils;
private String applicationJson = "application/json";
private String applicationStr = "application/X-WWW-form-urlencoded";
@GetMapping("/testGet")
public String testGet(String a) {
return "Get-调用成功!";
}
@PutMapping("/testPut")
public String testPut(String a) {
return "Put-调用成功!";
}
@DeleteMapping("/testDelete")
public String testDelete(String a) {
return "Delete-调用成功!";
}
@PostMapping("/testPost")
public String testPost(String a) {
return "Post-调用成功!";
}
@GetMapping("/test")
public String testtre() throws IOException {
Map<String, String> parm = new HashMap<String, String>();
parm.put("a","123");
String wxResult = httpClientUtils.get("http://127.0.0.1:8010/testGet",parm);
// String wxResult = httpClientUtils.put("http://127.0.0.1:8010/testPut",parm);
// String wxResult = httpClientUtils.delete("http://127.0.0.1:8010/testDelete",parm);
// String wxResult = httpClientUtils.post("http://127.0.0.1:8010/testPost",parm,parm);
return wxResult;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


