HttpClient中post请求http、https示例

超、凢脫俗 2022-05-14 02:59 546阅读 0赞

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

  1. 创建CloseableHttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
  4. 调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
  5. 调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
  6. 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
  7. 释放连接。无论执行方法是否成功,都必须释放连接

具体代码如下(HttpClient-4.4.1):

复制代码

  1. /**
  2. * 简单httpclient实例
  3. *
  4. * @author arron
  5. * @date 2015年11月11日 下午6:36:49
  6. * @version 1.0
  7. */
  8. public class SimpleHttpClientDemo {
  9. /**
  10. * 模拟请求
  11. *
  12. * @param url 资源地址
  13. * @param map 参数列表
  14. * @param encoding 编码
  15. * @return
  16. * @throws ParseException
  17. * @throws IOException
  18. */
  19. public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{
  20. String body = "";
  21. //创建httpclient对象
  22. CloseableHttpClient client = HttpClients.createDefault();
  23. //创建post方式请求对象
  24. HttpPost httpPost = new HttpPost(url);
  25. //装填参数
  26. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  27. if(map!=null){
  28. for (Entry<String, String> entry : map.entrySet()) {
  29. nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  30. }
  31. }
  32. //设置参数到请求对象中
  33. httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
  34. System.out.println("请求地址:"+url);
  35. System.out.println("请求参数:"+nvps.toString());
  36. //设置header信息
  37. //指定报文头【Content-type】、【User-Agent】
  38. httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
  39. httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  40. //执行请求操作,并拿到结果(同步阻塞)
  41. CloseableHttpResponse response = client.execute(httpPost);
  42. //获取结果实体
  43. HttpEntity entity = response.getEntity();
  44. if (entity != null) {
  45. //按指定编码转换结果实体为String类型
  46. body = EntityUtils.toString(entity, encoding);
  47. }
  48. EntityUtils.consume(entity);
  49. //释放链接
  50. response.close();
  51. return body;
  52. }
  53. }

复制代码

对于HTTPS的访问,采取绕过证书的策略:

复制代码

  1. /**
  2. * 绕过验证
  3. *
  4. * @return
  5. * @throws NoSuchAlgorithmException
  6. * @throws KeyManagementException
  7. */
  8. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  9. SSLContext sc = SSLContext.getInstance("SSLv3");
  10. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  11. X509TrustManager trustManager = new X509TrustManager() {
  12. @Override
  13. public void checkClientTrusted(
  14. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  15. String paramString) throws CertificateException {
  16. }
  17. @Override
  18. public void checkServerTrusted(
  19. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  20. String paramString) throws CertificateException {
  21. }
  22. @Override
  23. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  24. return null;
  25. }
  26. };
  27. sc.init(null, new TrustManager[] { trustManager }, null);
  28. return sc;
  29. }

复制代码

然后修改原来的send方法:

复制代码

  1. /**
  2. * 模拟请求
  3. *
  4. * @param url 资源地址
  5. * @param map 参数列表
  6. * @param encoding 编码
  7. * @return
  8. * @throws NoSuchAlgorithmException
  9. * @throws KeyManagementException
  10. * @throws IOException
  11. * @throws ClientProtocolException
  12. */
  13. public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
  14. String body = "";
  15. //采用绕过验证的方式处理https请求
  16. SSLContext sslcontext = createIgnoreVerifySSL();
  17. // 设置协议http和https对应的处理socket链接工厂的对象
  18. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  19. .register("http", PlainConnectionSocketFactory.INSTANCE)
  20. .register("https", new SSLConnectionSocketFactory(sslcontext))
  21. .build();
  22. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  23. HttpClients.custom().setConnectionManager(connManager);
  24. //创建自定义的httpclient对象
  25. CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
  26. // CloseableHttpClient client = HttpClients.createDefault();
  27. //创建post方式请求对象
  28. HttpPost httpPost = new HttpPost(url);
  29. //装填参数
  30. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  31. if(map!=null){
  32. for (Entry<String, String> entry : map.entrySet()) {
  33. nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  34. }
  35. }
  36. //设置参数到请求对象中
  37. httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
  38. System.out.println("请求地址:"+url);
  39. System.out.println("请求参数:"+nvps.toString());
  40. //设置header信息
  41. //指定报文头【Content-type】、【User-Agent】
  42. httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
  43. httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  44. //执行请求操作,并拿到结果(同步阻塞)
  45. CloseableHttpResponse response = client.execute(httpPost);
  46. //获取结果实体
  47. HttpEntity entity = response.getEntity();
  48. if (entity != null) {
  49. //按指定编码转换结果实体为String类型
  50. body = EntityUtils.toString(entity, encoding);
  51. }
  52. EntityUtils.consume(entity);
  53. //释放链接
  54. response.close();
  55. return body;
  56. }

复制代码

但是,如果是自己用jdk或者其他工具生成的证书,还是希望用其他方式认证自签名的证书,这篇文章就来分享一下如何设置信任自签名的证书。当然你也可以参考官网示例中。

要想信任自签名的证书,必须得知道密钥库的路径及密钥库的密码。然后加载到程序来才可以。具体代码如下:

复制代码

  1. /**
  2. * 设置信任自签名证书
  3. *
  4. * @param keyStorePath 密钥库路径
  5. * @param keyStorepass 密钥库密码
  6. * @return
  7. */
  8. public static SSLContext custom(String keyStorePath, String keyStorepass){
  9. SSLContext sc = null;
  10. FileInputStream instream = null;
  11. KeyStore trustStore = null;
  12. try {
  13. trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  14. instream = new FileInputStream(new File(keyStorePath));
  15. trustStore.load(instream, keyStorepass.toCharArray());
  16. // 相信自己的CA和所有自签名的证书
  17. sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
  18. } catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) {
  19. e.printStackTrace();
  20. } finally {
  21. try {
  22. instream.close();
  23. } catch (IOException e) {
  24. }
  25. }
  26. return sc;
  27. }

复制代码

然后修改原来的send方法:

复制代码

  1. /**
  2. * 模拟请求
  3. *
  4. * @param url 资源地址
  5. * @param map 参数列表
  6. * @param encoding 编码
  7. * @return
  8. * @throws ParseException
  9. * @throws IOException
  10. * @throws KeyManagementException
  11. * @throws NoSuchAlgorithmException
  12. * @throws ClientProtocolException
  13. */
  14. public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException {
  15. String body = "";
  16. //tomcat是我自己的密钥库的密码,你可以替换成自己的
  17. //如果密码为空,则用"nopassword"代替
  18. SSLContext sslcontext = custom("D:\\keys\\wsriakey", "tomcat");
  19. // 设置协议http和https对应的处理socket链接工厂的对象
  20. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  21. .register("http", PlainConnectionSocketFactory.INSTANCE)
  22. .register("https", new SSLConnectionSocketFactory(sslcontext))
  23. .build();
  24. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  25. HttpClients.custom().setConnectionManager(connManager);
  26. //创建自定义的httpclient对象
  27. CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
  28. // CloseableHttpClient client = HttpClients.createDefault();
  29. //创建post方式请求对象
  30. HttpPost httpPost = new HttpPost(url);
  31. //装填参数
  32. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  33. if(map!=null){
  34. for (Entry<String, String> entry : map.entrySet()) {
  35. nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  36. }
  37. }
  38. //设置参数到请求对象中
  39. httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
  40. System.out.println("请求地址:"+url);
  41. System.out.println("请求参数:"+nvps.toString());
  42. //设置header信息
  43. //指定报文头【Content-type】、【User-Agent】
  44. httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
  45. httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  46. //执行请求操作,并拿到结果(同步阻塞)
  47. CloseableHttpResponse response = client.execute(httpPost);
  48. //获取结果实体
  49. HttpEntity entity = response.getEntity();
  50. if (entity != null) {
  51. //按指定编码转换结果实体为String类型
  52. body = EntityUtils.toString(entity, encoding);
  53. }
  54. EntityUtils.consume(entity);
  55. //释放链接
  56. response.close();
  57. return body;
  58. }

复制代码

发表评论

表情:
评论列表 (有 0 条评论,546人围观)

还没有评论,来说两句吧...

相关阅读