Commons-HttpClient原来是Apache Commons项目下的一个组件,现已被HttpComponents项目下的HttpClient组件所取代;作为调用Http接口的一种选择,本文介绍下其使用方法。文中所使用到的软件版本:Java 1.8.0_191、Commons-HttpClient 3.1。

1、服务端

参见Java调用Http接口(1)--编写服务端

2、调用Http接口

2.1、GET请求

  1. public static void get() {
  2. try {
  3. String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
  4. HttpClient httpClient = new HttpClient();
  5. GetMethod get = new GetMethod(requestPath);
  6. int status = httpClient.executeMethod(get);
  7. if (status == HttpStatus.SC_OK) {
  8. System.out.println("GET返回结果:" + new String(get.getResponseBody()));
  9. } else {
  10. System.out.println("GET返回状态码:" + status);
  11. }
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }
  15. }

2.2、POST请求(发送键值对数据)

  1. public static void post() {
  2. try {
  3. String requestPath = "http://localhost:8080/demo/httptest/getUser";
  4. HttpClient httpClient = new HttpClient();
  5. PostMethod post = new PostMethod(requestPath);
  6. post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
  7. String param = "userId=1000&userName=李白";
  8. post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
  9. int status = httpClient.executeMethod(post);
  10. if (status == HttpStatus.SC_OK) {
  11. System.out.println("POST返回结果:" + new String(post.getResponseBody()));
  12. } else {
  13. System.out.println("POST返回状态码:" + status);
  14. }
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. }
  18. }

2.3、POST请求(发送JSON数据)

  1. public static void post2() {
  2. try {
  3. String requestPath = "http://localhost:8080/demo/httptest/addUser";
  4. HttpClient httpClient = new HttpClient();
  5. PostMethod post = new PostMethod(requestPath);
  6. post.addRequestHeader("Content-type", "application/json");
  7. String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
  8. post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
  9. int status = httpClient.executeMethod(post);
  10. if (status == HttpStatus.SC_OK) {
  11. System.out.println("POST json返回结果:" + new String(post.getResponseBody()));
  12. } else {
  13. System.out.println("POST json返回状态码:" + status);
  14. }
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. }
  18. }

2.4、上传文件

  1. public static void upload() {
  2. try {
  3. String requestPath = "http://localhost:8080/demo/httptest/upload";
  4. HttpClient httpClient = new HttpClient();
  5. PostMethod post = new PostMethod(requestPath);
  6. FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
  7. post.setRequestEntity(new InputStreamRequestEntity(fileInputStream));
  8. int status = httpClient.executeMethod(post);
  9. if (status == HttpStatus.SC_OK) {
  10. System.out.println("upload返回结果:" + new String(post.getResponseBody()));
  11. } else {
  12. System.out.println("upload返回状态码:" + status);
  13. }
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }

2.5、上传文件及发送键值对数据

  1. public static void multi() {
  2. try {
  3. String requestPath = "http://localhost:8080/demo/httptest/multi";
  4. HttpClient httpClient = new HttpClient();
  5. PostMethod post = new PostMethod(requestPath);
  6.  
  7. File file = new File("d:/a.jpg");
  8. Part[] parts = {new FilePart("file", file), new StringPart("param1", "参数1", "utf-8"), new StringPart("param2", "参数2", "utf-8")};
  9.  
  10. post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
  11. int status = httpClient.executeMethod(post);
  12. if (status == HttpStatus.SC_OK) {
  13. System.out.println("multi返回结果:" + new String(post.getResponseBody()));
  14. } else {
  15. System.out.println("multi返回状态码:" + status);
  16. }
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }

2.6、完整例子

  1. package com.inspur.demo.http.client;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.net.URLEncoder;
  6.  
  7. import org.apache.commons.httpclient.HttpClient;
  8. import org.apache.commons.httpclient.HttpStatus;
  9. import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
  10. import org.apache.commons.httpclient.methods.GetMethod;
  11. import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
  12. import org.apache.commons.httpclient.methods.PostMethod;
  13. import org.apache.commons.httpclient.methods.multipart.FilePart;
  14. import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
  15. import org.apache.commons.httpclient.methods.multipart.Part;
  16. import org.apache.commons.httpclient.methods.multipart.StringPart;
  17.  
  18. /**
  19. *
  20. * 通过Commons-HttpClient调用Http接口
  21. *
  22. */
  23. public class CommonsHttpClientCase {
  24. /**
  25. * GET请求
  26. */
  27. public static void get() {
  28. try {
  29. String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
  30. HttpClient httpClient = new HttpClient();
  31. GetMethod get = new GetMethod(requestPath);
  32. int status = httpClient.executeMethod(get);
  33. if (status == HttpStatus.SC_OK) {
  34. System.out.println("GET返回结果:" + new String(get.getResponseBody()));
  35. } else {
  36. System.out.println("GET返回状态码:" + status);
  37. }
  38. } catch (Exception e) {
  39. e.printStackTrace();
  40. }
  41. }
  42.  
  43. /**
  44. * POST请求(发送键值对数据)
  45. */
  46. public static void post() {
  47. try {
  48. String requestPath = "http://localhost:8080/demo/httptest/getUser";
  49. HttpClient httpClient = new HttpClient();
  50. PostMethod post = new PostMethod(requestPath);
  51. post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
  52. String param = "userId=1000&userName=李白";
  53. post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
  54. int status = httpClient.executeMethod(post);
  55. if (status == HttpStatus.SC_OK) {
  56. System.out.println("POST返回结果:" + new String(post.getResponseBody()));
  57. } else {
  58. System.out.println("POST返回状态码:" + status);
  59. }
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64.  
  65. /**
  66. * POST请求(发送json数据)
  67. */
  68. public static void post2() {
  69. try {
  70. String requestPath = "http://localhost:8080/demo/httptest/addUser";
  71. HttpClient httpClient = new HttpClient();
  72. PostMethod post = new PostMethod(requestPath);
  73. post.addRequestHeader("Content-type", "application/json");
  74. String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
  75. post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
  76. int status = httpClient.executeMethod(post);
  77. if (status == HttpStatus.SC_OK) {
  78. System.out.println("POST json返回结果:" + new String(post.getResponseBody()));
  79. } else {
  80. System.out.println("POST json返回状态码:" + status);
  81. }
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. }
  85. }
  86.  
  87. /**
  88. * 上传文件
  89. */
  90. public static void upload() {
  91. try {
  92. String requestPath = "http://localhost:8080/demo/httptest/upload";
  93. HttpClient httpClient = new HttpClient();
  94. PostMethod post = new PostMethod(requestPath);
  95. FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
  96. post.setRequestEntity(new InputStreamRequestEntity(fileInputStream));
  97. int status = httpClient.executeMethod(post);
  98. if (status == HttpStatus.SC_OK) {
  99. System.out.println("upload返回结果:" + new String(post.getResponseBody()));
  100. } else {
  101. System.out.println("upload返回状态码:" + status);
  102. }
  103. } catch (Exception e) {
  104. e.printStackTrace();
  105. }
  106. }
  107.  
  108. /**
  109. * 上传文件及发送键值对数据
  110. */
  111. public static void multi() {
  112. try {
  113. String requestPath = "http://localhost:8080/demo/httptest/multi";
  114. HttpClient httpClient = new HttpClient();
  115. PostMethod post = new PostMethod(requestPath);
  116.  
  117. File file = new File("d:/a.jpg");
  118. Part[] parts = {new FilePart("file", file), new StringPart("param1", "参数1", "utf-8"), new StringPart("param2", "参数2", "utf-8")};
  119.  
  120. post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
  121. int status = httpClient.executeMethod(post);
  122. if (status == HttpStatus.SC_OK) {
  123. System.out.println("multi返回结果:" + new String(post.getResponseBody()));
  124. } else {
  125. System.out.println("multi返回状态码:" + status);
  126. }
  127. } catch (Exception e) {
  128. e.printStackTrace();
  129. }
  130. }
  131.  
  132. public static void main(String[] args) {
  133. get();
  134. post();
  135. post2();
  136. upload();
  137. multi();
  138. }
  139.  
  140. }

3、调用Https接口

与调用Http接口不一样的部分主要在设置ssl部分,设置方法是自己实现ProtocolSocketFactory接口;其ssl的设置与HttpsURLConnection很相似(参见Java调用Http/Https接口(2)--HttpURLConnection/HttpsURLConnection调用Http/Https接口);下面用GET请求来演示ssl的设置,其他调用方式类似。

  1. package com.inspur.demo.http.client;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.net.InetAddress;
  7. import java.net.InetSocketAddress;
  8. import java.net.Socket;
  9. import java.net.SocketAddress;
  10. import java.net.UnknownHostException;
  11. import java.security.KeyStore;
  12. import java.security.cert.CertificateException;
  13. import java.security.cert.X509Certificate;
  14.  
  15. import javax.net.ssl.KeyManager;
  16. import javax.net.ssl.KeyManagerFactory;
  17. import javax.net.ssl.SSLContext;
  18. import javax.net.ssl.SSLSocketFactory;
  19. import javax.net.ssl.TrustManager;
  20. import javax.net.ssl.TrustManagerFactory;
  21. import javax.net.ssl.X509TrustManager;
  22.  
  23. import org.apache.commons.httpclient.ConnectTimeoutException;
  24. import org.apache.commons.httpclient.HttpClient;
  25. import org.apache.commons.httpclient.methods.GetMethod;
  26. import org.apache.commons.httpclient.params.HttpConnectionParams;
  27. import org.apache.commons.httpclient.protocol.Protocol;
  28. import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
  29.  
  30. import com.inspur.demo.common.util.FileUtil;
  31.  
  32. /**
  33. *
  34. * 通过Commons-HttpClient调用Https接口
  35. *
  36. */
  37. public class CommonsHttpClientHttpsCase {
  38.  
  39. public static void main(String[] args) {
  40. try {
  41. HttpClient httpClient = new HttpClient();
  42. /*
  43. * 请求有权威证书的地址
  44. */
  45. String requestPath = "https://www.baidu.com/";
  46. GetMethod get = new GetMethod(requestPath);
  47. httpClient.executeMethod(get);
  48. System.out.println("GET1返回结果:" + new String(get.getResponseBody()));
  49.  
  50. /*
  51. * 请求自定义证书的地址
  52. */
  53. //获取信任证书库
  54. KeyStore trustStore = getkeyStore("jks", "d:/temp/cacerts", "123456");
  55.  
  56. //不需要客户端证书
  57. requestPath = "https://10.40.103.48:9010/zsywservice";
  58. Protocol.registerProtocol("https", new Protocol("https", new HttpsProtocolSocketFactory(trustStore), 443));
  59. get = new GetMethod(requestPath);
  60. httpClient.executeMethod(get);
  61. System.out.println("GET2返回结果:" + new String(get.getResponseBody()));
  62.  
  63. //需要客户端证书
  64. requestPath = "https://10.40.103.48:9016/zsywservice";
  65. KeyStore keyStore = getkeyStore("pkcs12", "d:/client.p12", "123456");
  66. Protocol.registerProtocol("https", new Protocol("https", new HttpsProtocolSocketFactory(keyStore, "123456", trustStore), 443));
  67. get = new GetMethod(requestPath);
  68. httpClient.executeMethod(get);
  69. System.out.println("GET3返回结果:" + new String(get.getResponseBody()));
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. }
  74.  
  75. /**
  76. * 获取证书
  77. * @return
  78. */
  79. private static KeyStore getkeyStore(String type, String filePath, String password) {
  80. KeyStore keySotre = null;
  81. FileInputStream in = null;
  82. try {
  83. keySotre = KeyStore.getInstance(type);
  84. in = new FileInputStream(new File(filePath));
  85. keySotre.load(in, password.toCharArray());
  86. } catch (Exception e) {
  87. e.printStackTrace();
  88. } finally {
  89. FileUtil.close(in);
  90. }
  91. return keySotre;
  92. }
  93. }
  94.  
  95. final class HttpsProtocolSocketFactory implements ProtocolSocketFactory {
  96. private KeyStore keyStore;
  97. private String keyStorePassword;
  98. private KeyStore trustStore;
  99. private SSLSocketFactory sslSocketFactory = null;
  100.  
  101. public HttpsProtocolSocketFactory(KeyStore keyStore, String keyStorePassword, KeyStore trustStore) {
  102. this.keyStore = keyStore;
  103. this.keyStorePassword = keyStorePassword;
  104. this.trustStore = trustStore;
  105. }
  106.  
  107. public HttpsProtocolSocketFactory(KeyStore trustStore) {
  108. this.trustStore = trustStore;
  109. }
  110.  
  111. private SSLSocketFactory getSSLSocketFactory() {
  112. if (sslSocketFactory != null) {
  113. return sslSocketFactory;
  114. }
  115. try {
  116. KeyManager[] keyManagers = null;
  117. TrustManager[] trustManagers = null;
  118. if (keyStore != null) {
  119. KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
  120. keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
  121. keyManagers = keyManagerFactory.getKeyManagers();
  122. }
  123. if (trustStore != null) {
  124. TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
  125. trustManagerFactory.init(trustStore);
  126. trustManagers = trustManagerFactory.getTrustManagers();
  127. } else {
  128. trustManagers = new TrustManager[] { new DefaultTrustManager() };
  129. }
  130.  
  131. SSLContext context = SSLContext.getInstance("TLSv1.2");
  132. context.init(keyManagers, trustManagers, null);
  133. sslSocketFactory = context.getSocketFactory();
  134. return sslSocketFactory;
  135. } catch (Exception e) {
  136. e.printStackTrace();
  137. }
  138. return null;
  139. }
  140.  
  141. @Override
  142. public Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
  143. throws IOException, UnknownHostException {
  144. return getSSLSocketFactory().createSocket(host, port, localAddress, localPort);
  145. }
  146.  
  147. @Override
  148. public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
  149. HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
  150. if (params == null) {
  151. throw new IllegalArgumentException("Parameters may not be null");
  152. }
  153. int timeout = params.getConnectionTimeout();
  154. if (timeout == 0) {
  155. return getSSLSocketFactory().createSocket(host, port, localAddress, localPort);
  156. } else {
  157. Socket socket = getSSLSocketFactory().createSocket();
  158. SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
  159. SocketAddress remoteAddr = new InetSocketAddress(host, port);
  160. socket.bind(localAddr);
  161. socket.connect(remoteAddr, timeout);
  162. return socket;
  163. }
  164. }
  165.  
  166. @Override
  167. public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
  168. return getSSLSocketFactory().createSocket(host, port);
  169. }
  170.  
  171. }
  172.  
  173. final class DefaultTrustManager implements X509TrustManager {
  174. @Override
  175. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  176. }
  177.  
  178. @Override
  179. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  180. }
  181.  
  182. @Override
  183. public X509Certificate[] getAcceptedIssuers() {
  184. return null;
  185. }
  186. }

Java调用Http/Https接口(3)--Commons-HttpClient调用Http/Https接口的更多相关文章

  1. SpringMVC 结合HttpClient调用第三方接口实现

    使用HttpClient 依赖jar包 1:commons-httpclient-3.0.jar 2:commons-logging-1.1.1.jar 3:commons-codec-1.6.jar ...

  2. httpclient调用https

    httpclient调用https报错: Exception in thread "main" java.lang.Exception: sun.security.validato ...

  3. java apache commons HttpClient发送get和post请求的学习整理(转)

    文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...

  4. Java发布webservice应用并发送SOAP请求调用

    webservice框架有很多,比如axis.axis2.cxf.xFire等等,做服务端和做客户端都可行,个人感觉使用这些框架的好处是减少了对于接口信息的解析,最主要的是减少了对于传递于网络中XML ...

  5. httpclient跳过https请求的验证

    一.因为在使用https发送请求的时候会涉及,验证方式.但是这种方式在使用的时候很不方便.特别是在请求外部接口的时候,所以这我写了一个跳过验证的方式.(供参考) 二.加入包,这里用的是commons- ...

  6. org.apache.commons.httpclient.HttpClient的使用(转)

    HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java net包中已经提供了访 ...

  7. Java网络编程:利用apache的HttpClient包进行http操作

    本文介绍如何利用apache的HttpClient包进行http操作,包括get操作和post操作. 一.下面的代码是对HttpClient包的封装,以便于更好的编写应用代码. import java ...

  8. Java调用Http/Https接口(4)--HttpClient调用Http/Https接口

    HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似.文中所使用到的软件版本:Java 1.8. ...

  9. java 通过httpclient调用https 的webapi

    java如何通过httpclient 调用采用https方式的webapi?如何验证证书.示例:https://devdata.osisoft.com/p...需要通过httpclient调用该接口, ...

  10. Java之HttpClient调用WebService接口发送短信源码实战

    摘要 Java之HttpClient调用WebService接口发送短信源码实战 一:接口文档 二:WSDL 三:HttpClient方法 HttpClient方法一 HttpClient方法二 Ht ...

随机推荐

  1. java并发编程(二)synchronized

    参考文章: http://blog.csdn.net/javazejian/article/details/72828483http://ifeve.com/java-synchronized/htt ...

  2. [Gamma阶段]第五次Scrum Meeting

    Scrum Meeting博客目录 [Gamma阶段]第五次Scrum Meeting 基本信息 名称 时间 地点 时长 第五次Scrum Meeting 19/05/31 大运村寝室6楼 30min ...

  3. MySQL事务隔离级别(二)

    搞清楚MySQL事务隔离级别 首先创建一个表 account.创建表的过程略过(由于 InnoDB 存储引擎支持事务,所以将表的存储引擎设置为 InnoDB).表的结构如下: 为了说明问题,我们打开两 ...

  4. SpringBoot——Profile多环境支持

    1.多profile文件形式 主配置文件编写时, 文件名可以是application-{profile}.properties/yml 默认使用的application.properties的配置. ...

  5. Microsoft.Owin 使用 文件服务

    添加引用: <package id="Microsoft.Owin" version="4.0.1" targetFramework="net4 ...

  6. vue npm run dev 报错 semver\semver.js:312 throw new TypeError('Invalid Version: ' + version)

    npm run dev运行报错信息如下图: 原因分析: 版本问题 解决办法: 在semver.js(node_modules/semver/semver.js)里做了一些改动,代码如下: // if ...

  7. android ------ 高版本的 Tablayout 下划线宽度

    前面呢,有写过TabLayout的博客,最近开发用到了高本版遇到一些问题,来总结一下 Android--------TabLayout实现新闻客户端顶部导航栏 Android中Tablayout设置下 ...

  8. 【Node.js】Node.js的安装

    Node.js的简介 简单的说,Node.js 是运行在服务端的 JavaScript. Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台. Node.js是一个事件 ...

  9. Openresty与Tengine

    Tengine官方网站:http://tengine.taobao.org/index_cn.html OpenResty官方网站:http://openresty.org/ Openresty和Te ...

  10. 946. Validate Stack Sequences

    946. Validate Stack Sequences class Solution { public: bool validateStackSequences(vector<int> ...