apache httpclient 4 范例
下面是一个通过apache httpclient 4 实现http/https的普通访问和BasicAuth认证访问的例子。依赖的第三方库为:

下面是具体实现:
package test; import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import javax.net.ssl.SSLContext; import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
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.client.methods.HttpRequestBase;
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.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
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; /**
* HttpClient的包装类,支持http/https的普通访问和basic Auth认证访问
* @author needle
*
*/
public class HttpUtilDemo {
//默认超时时间
private static final int DEFAULT_TIMEOUT = 5000; public static class HttpResult{
public final int STATUS;
public String CONTENT; public HttpResult(int status, String content){
this.STATUS = status;
this.CONTENT = content;
}
} private static void setTimeout(HttpRequestBase post) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(DEFAULT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_TIMEOUT)
.setSocketTimeout(DEFAULT_TIMEOUT).build(); post.setConfig(requestConfig);
} //这里是同时支持http/https的关键
private static CloseableHttpClient getHttpClient(HttpClientBuilder httpClientBuilder) {
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); //构建客户端
return httpClientBuilder.setConnectionManager(connManager).build();
} //获取普通访问的HttpClient
private static CloseableHttpClient getHttpClient() {
return getHttpClient(HttpClientBuilder.create());
} //获取支持basic Auth认证的HttpClient
private static CloseableHttpClient getHttpClientWithBasicAuth(String username, String password){
return getHttpClient(credential(username, password));
} //配置basic Auth 认证
private static HttpClientBuilder credential(String username, String password) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CredentialsProvider provider = new BasicCredentialsProvider();
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
provider.setCredentials(scope, credentials);
httpClientBuilder.setDefaultCredentialsProvider(provider);
return httpClientBuilder;
} //设置头信息,e.g. content-type 等
private static void setHeaders(HttpRequestBase req, Map<String, String> headers){
if(headers == null) return; for(Entry<String, String> header : headers.entrySet()){
req.setHeader(header.getKey(), header.getValue());
}
} /**
* get基础类,支持普通访问和Basic Auth认证
* @param uri
* @param headers
* @param client 不同的方式不同的HttpClient
* @param isTimeout 是否超时
* @return
*/
private static HttpResult get(String uri, Map<String, String> headers, CloseableHttpClient client, boolean isTimeout){
try(CloseableHttpClient httpClient = client){ HttpGet get = new HttpGet(uri);
setHeaders(get, headers); if(isTimeout){
setTimeout(get);
} try(CloseableHttpResponse httpResponse = httpClient.execute(get)){
int status = httpResponse.getStatusLine().getStatusCode();
if(status != HttpStatus.SC_NOT_FOUND){
return new HttpResult(status, IOUtils.toString(httpResponse.getEntity().getContent(), "utf-8"));
}else{
return new HttpResult(status, "404");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static HttpResult get(String uri, Map<String, String> headers, boolean isTimeout){
return get(uri, headers, getHttpClient(), isTimeout);
} public static HttpResult getWithBaiscAuth(String uri, Map<String, String> headers, String username, String password, boolean isTimeout){
return get(uri, headers, getHttpClientWithBasicAuth(username, password), isTimeout);
} public static HttpEntity createUrlEncodedFormEntity(Map<String, String> params){
List<NameValuePair> data = new ArrayList<>();
for(Map.Entry<String, String> entry : params.entrySet()){
data.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
return new UrlEncodedFormEntity(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} public static HttpEntity createStringEntity(String body){
try {
return new StringEntity(body);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} private static HttpResult post(CloseableHttpClient client, String uri, Map<String, String> headers, HttpEntity entity, boolean isTimeout){
try(CloseableHttpClient httpClient = client){
HttpPost post = new HttpPost(uri);
setHeaders(post, headers);
if(isTimeout){
setTimeout(post);
}
post.setEntity(entity);
try(CloseableHttpResponse httpResponse = httpClient.execute(post)){
int status = httpResponse.getStatusLine().getStatusCode(); if(status != HttpStatus.SC_NOT_FOUND){
return new HttpResult(status, IOUtils.toString(httpResponse.getEntity().getContent(), "utf-8"));
}else{
return new HttpResult(status, "404");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} public static HttpResult post(String uri, Map<String, String> headers, HttpEntity entity, boolean isTimeout){
return post(getHttpClient(), uri,headers, entity, isTimeout);
} public static HttpResult postWithBasicAuth(String uri, Map<String, String> headers, String username, String password, HttpEntity entity, boolean isTimeout){
return post(getHttpClientWithBasicAuth(username, password), uri, headers, entity, isTimeout);
} public static void main(String[] args) throws UnsupportedEncodingException {
Map<String, String> headers = new HashMap<String, String>();
headers.put("isClient","true");
headers.put("content-type", "application/xml");
headers.put("content-encoding", "UTF-8"); String body = "<action><status></status><fault><reason></reason><detail></detail></fault></action>"; //测试操作Ovirt 虚拟机
HttpResult result = postWithBasicAuth("https://192.168.104.71/api/vms/41feaa71-4cb9-4c22-9380-ee530143eb0d/stop", headers, "sysadmin@internal", "admin==1", new StringEntity(body), false); System.out.println(result.STATUS);
System.out.println(result.CONTENT);
}
}
apache httpclient 4 范例的更多相关文章
- 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类
推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...
- 论httpclient上传带参数【commons-httpclient和apache httpclient区别】
需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...
- Apache HttpClient使用之阻塞陷阱
前言: 之前做个一个数据同步的定时程序. 其内部集成了某电商的SDK(简单的Apache Httpclient4.x封装)+Spring Quartz来实现. 原本以为简单轻松, 喝杯咖啡就高枕无忧的 ...
- Android 6.0删除Apache HttpClient相关类的解决方法
相应的官方文档如下: 上面文档的大致意思是,在Android 6.0(API 23)中,Google已经移除了Apache HttpClient相关的类,推荐使用HttpUrlConnection. ...
- android 中对apache httpclient及httpurlconnection的选择
在官方blog中,android工程师谈到了如何去选择apache client和httpurlconnection的问题: 原文见http://android-developers.blogspot ...
- 新旧apache HttpClient 获取httpClient方法
在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...
- 基于apache httpclient 调用Face++ API
简要: 本文简要介绍使用Apache HttpClient工具调用旷世科技的Face API. 前期准备: 依赖包maven地址: <!-- https://mvnrepository.com/ ...
- 一个封装的使用Apache HttpClient进行Http请求(GET、POST、PUT等)的类。
一个封装的使用Apache HttpClient进行Http请求(GET.POST.PUT等)的类. import com.qunar.payment.gateway.front.channel.mp ...
- RESTful Java client with Apache HttpClient / URL /Jersey client
JSON example with Jersey + Jackson Jersey client examples RESTful Java client with RESTEasy client f ...
随机推荐
- Android 开源框架 -Toasty
GitHub地址 用法: 第一步:根目录的 build.gradle: allprojects { repositories { ... maven { url "https://jitpa ...
- 用git上传项目到GitHub或者码云全过程
用git上传项目到GitHub或者码云全过程 1. 会生成一个隐藏文件夹".git".这是一个不可删文件,因为暂存区和历史区还有一些其他的信息都在这里,删掉就不是一个完整的仓库了 ...
- 【老孟Flutter】2020年总结
2020年是我经历的最不平凡的一年,这一年有遗憾.有收获,有感概,也有庆幸,庆幸自己还活着. 用一句话总结自己的2020,忙并收获着,累并快乐着. <Flutter 实战入门> <F ...
- 多个table表不同数据切换 easyui中
未处理 有效 无效 切换显示 1.加载页面时将 未处理 ,无效 有效的数据分别查到,给对应的table赋值 <%--easyui 的 tab标签栏--%><div id=& ...
- 提高服务端性能的几个socket选项
提高服务端性能的几个socket选项 在之前的一篇文章中,作者在配置了SO_REUSEPORT选项之后,使得应用的性能提高了数十倍.现在介绍socket选项中如下几个可以提升服务端性能的选项: SO_ ...
- 循序渐进VUE+Element 前端应用开发(30)--- ABP后端和Vue+Element前端结合的分页排序处理
在很多列表展示数据的场合中,大多数都会需要一个排序的处理,以方便快速查找排序所需的数据,本篇随笔介绍如何结合ABP后端和Vue+Element前端结合的分页排序处理过程. 1.Vue+Element前 ...
- windows和Linux的文件路径
(1)windows的文件路径格式"E:\Python\workplace\codes"单反斜杠的方式,但是在很多编程语言中会不认识"\"字符,可能会把它识别成 ...
- golang语法笔记
开始微服务,那就先温习下golang语法吧; golang变量类型 1. 整形 Go %b 表示为二进制 %c 该值对应的unicode码值 %d 表示为十进制 %o 表示为八 ...
- Java8接口的默认方法
项目实战 实现上图接口的实现类有很多,其中有些实现类已经在生成环境了,现在需要新增几个实现类,都需要有回调方法,所以在接口中添加了一个回调的默认方法,如果使用接口的普通方法就得改所有实现了接口的实现类 ...
- STP、PVST、MST协议
• STP:生成树协议 ○ 阻止环形链路的广播风暴 • PVST:VLAN生成树 ○ 是STP的进阶版不仅能阻止广播风暴,还可以做到基于VLAN进行流量均衡. ...