Java调用Http/Https接口(3)--Commons-HttpClient调用Http/Https接口
Commons-HttpClient原来是Apache Commons项目下的一个组件,现已被HttpComponents项目下的HttpClient组件所取代;作为调用Http接口的一种选择,本文介绍下其使用方法。文中所使用到的软件版本:Java 1.8.0_191、Commons-HttpClient 3.1。
1、服务端
2、调用Http接口
2.1、GET请求
public static void get() {
try {
String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
HttpClient httpClient = new HttpClient();
GetMethod get = new GetMethod(requestPath);
int status = httpClient.executeMethod(get);
if (status == HttpStatus.SC_OK) {
System.out.println("GET返回结果:" + new String(get.getResponseBody()));
} else {
System.out.println("GET返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}
2.2、POST请求(发送键值对数据)
public static void post() {
try {
String requestPath = "http://localhost:8080/demo/httptest/getUser";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath);
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
String param = "userId=1000&userName=李白";
post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("POST返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("POST返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}
2.3、POST请求(发送JSON数据)
public static void post2() {
try {
String requestPath = "http://localhost:8080/demo/httptest/addUser";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath);
post.addRequestHeader("Content-type", "application/json");
String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("POST json返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("POST json返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}
2.4、上传文件
public static void upload() {
try {
String requestPath = "http://localhost:8080/demo/httptest/upload";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath);
FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
post.setRequestEntity(new InputStreamRequestEntity(fileInputStream));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("upload返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("upload返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}
2.5、上传文件及发送键值对数据
public static void multi() {
try {
String requestPath = "http://localhost:8080/demo/httptest/multi";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath);
File file = new File("d:/a.jpg");
Part[] parts = {new FilePart("file", file), new StringPart("param1", "参数1", "utf-8"), new StringPart("param2", "参数2", "utf-8")};
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("multi返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("multi返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}
2.6、完整例子
package com.inspur.demo.http.client; import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder; import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart; /**
*
* 通过Commons-HttpClient调用Http接口
*
*/
public class CommonsHttpClientCase {
/**
* GET请求
*/
public static void get() {
try {
String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
HttpClient httpClient = new HttpClient();
GetMethod get = new GetMethod(requestPath);
int status = httpClient.executeMethod(get);
if (status == HttpStatus.SC_OK) {
System.out.println("GET返回结果:" + new String(get.getResponseBody()));
} else {
System.out.println("GET返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* POST请求(发送键值对数据)
*/
public static void post() {
try {
String requestPath = "http://localhost:8080/demo/httptest/getUser";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath);
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
String param = "userId=1000&userName=李白";
post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("POST返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("POST返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* POST请求(发送json数据)
*/
public static void post2() {
try {
String requestPath = "http://localhost:8080/demo/httptest/addUser";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath);
post.addRequestHeader("Content-type", "application/json");
String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
post.setRequestEntity(new ByteArrayRequestEntity(param.getBytes()));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("POST json返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("POST json返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 上传文件
*/
public static void upload() {
try {
String requestPath = "http://localhost:8080/demo/httptest/upload";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath);
FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
post.setRequestEntity(new InputStreamRequestEntity(fileInputStream));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("upload返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("upload返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 上传文件及发送键值对数据
*/
public static void multi() {
try {
String requestPath = "http://localhost:8080/demo/httptest/multi";
HttpClient httpClient = new HttpClient();
PostMethod post = new PostMethod(requestPath); File file = new File("d:/a.jpg");
Part[] parts = {new FilePart("file", file), new StringPart("param1", "参数1", "utf-8"), new StringPart("param2", "参数2", "utf-8")}; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
int status = httpClient.executeMethod(post);
if (status == HttpStatus.SC_OK) {
System.out.println("multi返回结果:" + new String(post.getResponseBody()));
} else {
System.out.println("multi返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
get();
post();
post2();
upload();
multi();
} }
3、调用Https接口
与调用Http接口不一样的部分主要在设置ssl部分,设置方法是自己实现ProtocolSocketFactory接口;其ssl的设置与HttpsURLConnection很相似(参见Java调用Http/Https接口(2)--HttpURLConnection/HttpsURLConnection调用Http/Https接口);下面用GET请求来演示ssl的设置,其他调用方式类似。
package com.inspur.demo.http.client; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import com.inspur.demo.common.util.FileUtil; /**
*
* 通过Commons-HttpClient调用Https接口
*
*/
public class CommonsHttpClientHttpsCase { public static void main(String[] args) {
try {
HttpClient httpClient = new HttpClient();
/*
* 请求有权威证书的地址
*/
String requestPath = "https://www.baidu.com/";
GetMethod get = new GetMethod(requestPath);
httpClient.executeMethod(get);
System.out.println("GET1返回结果:" + new String(get.getResponseBody())); /*
* 请求自定义证书的地址
*/
//获取信任证书库
KeyStore trustStore = getkeyStore("jks", "d:/temp/cacerts", "123456"); //不需要客户端证书
requestPath = "https://10.40.103.48:9010/zsywservice";
Protocol.registerProtocol("https", new Protocol("https", new HttpsProtocolSocketFactory(trustStore), 443));
get = new GetMethod(requestPath);
httpClient.executeMethod(get);
System.out.println("GET2返回结果:" + new String(get.getResponseBody())); //需要客户端证书
requestPath = "https://10.40.103.48:9016/zsywservice";
KeyStore keyStore = getkeyStore("pkcs12", "d:/client.p12", "123456");
Protocol.registerProtocol("https", new Protocol("https", new HttpsProtocolSocketFactory(keyStore, "123456", trustStore), 443));
get = new GetMethod(requestPath);
httpClient.executeMethod(get);
System.out.println("GET3返回结果:" + new String(get.getResponseBody()));
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 获取证书
* @return
*/
private static KeyStore getkeyStore(String type, String filePath, String password) {
KeyStore keySotre = null;
FileInputStream in = null;
try {
keySotre = KeyStore.getInstance(type);
in = new FileInputStream(new File(filePath));
keySotre.load(in, password.toCharArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
FileUtil.close(in);
}
return keySotre;
}
} final class HttpsProtocolSocketFactory implements ProtocolSocketFactory {
private KeyStore keyStore;
private String keyStorePassword;
private KeyStore trustStore;
private SSLSocketFactory sslSocketFactory = null; public HttpsProtocolSocketFactory(KeyStore keyStore, String keyStorePassword, KeyStore trustStore) {
this.keyStore = keyStore;
this.keyStorePassword = keyStorePassword;
this.trustStore = trustStore;
} public HttpsProtocolSocketFactory(KeyStore trustStore) {
this.trustStore = trustStore;
} private SSLSocketFactory getSSLSocketFactory() {
if (sslSocketFactory != null) {
return sslSocketFactory;
}
try {
KeyManager[] keyManagers = null;
TrustManager[] trustManagers = null;
if (keyStore != null) {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
keyManagers = keyManagerFactory.getKeyManagers();
}
if (trustStore != null) {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(trustStore);
trustManagers = trustManagerFactory.getTrustManagers();
} else {
trustManagers = new TrustManager[] { new DefaultTrustManager() };
} SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(keyManagers, trustManagers, null);
sslSocketFactory = context.getSocketFactory();
return sslSocketFactory;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} @Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
throws IOException, UnknownHostException {
return getSSLSocketFactory().createSocket(host, port, localAddress, localPort);
} @Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
if (timeout == 0) {
return getSSLSocketFactory().createSocket(host, port, localAddress, localPort);
} else {
Socket socket = getSSLSocketFactory().createSocket();
SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
SocketAddress remoteAddr = new InetSocketAddress(host, port);
socket.bind(localAddr);
socket.connect(remoteAddr, timeout);
return socket;
}
} @Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return getSSLSocketFactory().createSocket(host, port);
} } final class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} @Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
Java调用Http/Https接口(3)--Commons-HttpClient调用Http/Https接口的更多相关文章
- SpringMVC 结合HttpClient调用第三方接口实现
使用HttpClient 依赖jar包 1:commons-httpclient-3.0.jar 2:commons-logging-1.1.1.jar 3:commons-codec-1.6.jar ...
- httpclient调用https
httpclient调用https报错: Exception in thread "main" java.lang.Exception: sun.security.validato ...
- java apache commons HttpClient发送get和post请求的学习整理(转)
文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...
- Java发布webservice应用并发送SOAP请求调用
webservice框架有很多,比如axis.axis2.cxf.xFire等等,做服务端和做客户端都可行,个人感觉使用这些框架的好处是减少了对于接口信息的解析,最主要的是减少了对于传递于网络中XML ...
- httpclient跳过https请求的验证
一.因为在使用https发送请求的时候会涉及,验证方式.但是这种方式在使用的时候很不方便.特别是在请求外部接口的时候,所以这我写了一个跳过验证的方式.(供参考) 二.加入包,这里用的是commons- ...
- org.apache.commons.httpclient.HttpClient的使用(转)
HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java net包中已经提供了访 ...
- Java网络编程:利用apache的HttpClient包进行http操作
本文介绍如何利用apache的HttpClient包进行http操作,包括get操作和post操作. 一.下面的代码是对HttpClient包的封装,以便于更好的编写应用代码. import java ...
- Java调用Http/Https接口(4)--HttpClient调用Http/Https接口
HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似.文中所使用到的软件版本:Java 1.8. ...
- java 通过httpclient调用https 的webapi
java如何通过httpclient 调用采用https方式的webapi?如何验证证书.示例:https://devdata.osisoft.com/p...需要通过httpclient调用该接口, ...
- Java之HttpClient调用WebService接口发送短信源码实战
摘要 Java之HttpClient调用WebService接口发送短信源码实战 一:接口文档 二:WSDL 三:HttpClient方法 HttpClient方法一 HttpClient方法二 Ht ...
随机推荐
- .htaccess tricks总结
目录 .htaccess tricks总结 一.什么是.htaccess 二.利用条件 三.利用方式 && tricks 1.将指定后缀名的文件当做php解析 2.php_value利 ...
- [技术博客] 用户验证码验证机制---redis缓存数据库的使用
目录 问题引入 初识redis 实际应用 作者:马振亚 问题引入 在这次的开发过程中,我们的需求中有一个是普通用户可以通过特定的机制申请成为社长.因为只有部分人才能验证成功,所以这个最开始想了两种思路 ...
- 冰多多团队-第五次Scrum会议
冰多多团队-第五次Scrum会议 工作情况 团队成员 已完成任务 待完成任务 zpj 部分Action整合, 接入语音接口,整合项目解决兼容性问题 ASR bug修复 牛雅哲 跑通了科大讯飞语法识别的 ...
- 【Gamma阶段】第三次Scrum Meeting
冰多多团队-Gamma阶段第三次Scrum会议 工作情况 团队成员 已完成任务 待完成任务 卓培锦 修改可移动button以及button手感反馈优化 编辑器风格切换(夜间模式) 牛雅哲 添加优化算法 ...
- Spring Boot打war包和jar包的目录结构简单讲解
Spring Boot项目可以制作成jar包和war包,其目录结构是不一样的,具体的如下所示: 1.war包目录结构分析WAR(Web Archivefile)网络应用程序文件,是与平台无关的文件格式 ...
- android细节之android.intent.category.DEFAULT的使用
我们知道,实现android的Activity之间相互跳转需要用到Intent, Intent又分为显式Intent和隐式Intent, 显式Intent很简单,比如我在FirstActivity中想 ...
- odoo开发笔记 -- 触发机制/埋点设置
场景描述: 项目需求中,经常会需要,当某个字段处某个特定状态时候,触发执行特定的方法:或者创建某条记录的时候,同时做另一个操作:如何实现类似的需求? 实现方式: odoo中提供了几种触发方式: 1. ...
- 分布式事务一2PC
分布式事务解决方案之2PC(两阶段提交) 前面已经学习了分布式事务的基础理论,以理论为基础,针对不同的分布式场景业界常见的解决方案有2PC.TCC.可靠消息最终一致性.最大努力通知这几种. 3.1.什 ...
- 使用gevent包实现concurrent.futures.executor 相同的公有方法。组成鸭子类
类名不同,但公有方法的名字和提供的基本功能大致相同,但两个类没有共同继承的祖先或者抽象类 接口来规定他,叫鸭子类. 使并发核心池能够在 threadpoolexetor和geventpoolexecu ...
- ubuntu16.04下安装运行PL-SLAM
PL-SLAM是Ruben Gomez-Ojeda大神融合点和线特征SLAM的最新成果,并开放了源代码,本博文记录安装运行PL-SLAM遇到的一些问题. 1源代码地址 https://github.c ...