下面是一个通过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 范例的更多相关文章

  1. 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类

    推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...

  2. 论httpclient上传带参数【commons-httpclient和apache httpclient区别】

    需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...

  3. Apache HttpClient使用之阻塞陷阱

    前言: 之前做个一个数据同步的定时程序. 其内部集成了某电商的SDK(简单的Apache Httpclient4.x封装)+Spring Quartz来实现. 原本以为简单轻松, 喝杯咖啡就高枕无忧的 ...

  4. Android 6.0删除Apache HttpClient相关类的解决方法

    相应的官方文档如下: 上面文档的大致意思是,在Android 6.0(API 23)中,Google已经移除了Apache HttpClient相关的类,推荐使用HttpUrlConnection. ...

  5. android 中对apache httpclient及httpurlconnection的选择

    在官方blog中,android工程师谈到了如何去选择apache client和httpurlconnection的问题: 原文见http://android-developers.blogspot ...

  6. 新旧apache HttpClient 获取httpClient方法

    在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...

  7. 基于apache httpclient 调用Face++ API

    简要: 本文简要介绍使用Apache HttpClient工具调用旷世科技的Face API. 前期准备: 依赖包maven地址: <!-- https://mvnrepository.com/ ...

  8. 一个封装的使用Apache HttpClient进行Http请求(GET、POST、PUT等)的类。

    一个封装的使用Apache HttpClient进行Http请求(GET.POST.PUT等)的类. import com.qunar.payment.gateway.front.channel.mp ...

  9. RESTful Java client with Apache HttpClient / URL /Jersey client

    JSON example with Jersey + Jackson Jersey client examples RESTful Java client with RESTEasy client f ...

随机推荐

  1. java字符统计+字符串压缩

    要实习了.突然发现自己好像什么都不会,就去看看题吧.在网上看到一个字符串压缩的题.看了一眼,感觉用python很简单.一个for循环+字典就可以搞定. 但是呢,主要还是java.下面就用java来实现 ...

  2. RocketMQ踩坑记

    一.前言 现在的主流消息队列基本都是kafka.RabbitMQ和RocketMQ,只有了解各自的优缺点才能在不同的场景选择合适的MQ,对比图如下: MQ对比图 本篇文章主要介绍我自己在跑官方demo ...

  3. HTML学习案例--仿淘宝商品信息

    步骤:1.布局分析 2.敲代码 考察知识点: 1.类选择器(素材第四天) 2.CSS关于display,padding,margin的应用 3.如何用div布局 总结: 如果想让一行有两组以上的字块, ...

  4. 第六章节 BJROBOT 动态导航壁障

    导航前说明:一定要确保你小车在构建好地图的基础上进行! 1.把小车平放在你想要构建地图区域的地板上,打开资料里的虚拟机,打开一个终端, ssh 过去主控端启动 roslaunch znjrobot b ...

  5. vue中携带token以及发送ajax

    在项目中基本登录都会存在token,而我们也就需要在每次发送ajax的时候就必须携带他.从而最有效的办法,就是在设置请求头携带token,这样设置一次后面的每一次都会携带着这个token. 一:设置请 ...

  6. UML第三次结对作业

    这个作业要求在哪里 https://edu.cnblogs.com/campus/fzzcxy/2018SE1/homework/11274 这个作业的目标 <学会使用专业的建模工具> 队 ...

  7. git-廖雪峰版教程学习笔记

  8. 风炫安全web安全学习第三十四节课 文件包含漏洞防御

    风炫安全web安全学习第三十四节课 文件包含漏洞防御 文件包含防御 在功能设计上不要把文件包含的对应文件放到前台去操作 过滤各种../,https://, http:// 配置php.ini文件 al ...

  9. 风炫安全WEB安全学习第二十六节课 XSS常见绕过防御技巧

    风炫安全WEB安全学习第二十六节课 XSS常见绕过防御技巧 XSS绕过-过滤-编码 核心思想 后台过滤了特殊字符,比如说

  10. Command3

    压缩和解压 gzip gunzip .gz 指定文件必须带后缀 gzip file filename.gz zip unzip .zip unzip filename.zip directory zi ...