下面是一个通过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中的Copy-On-Write容器

    http://ifeve.com/java-copy-on-write/ 什么是CopyOnWrite容器 CopyOnWrite容器即写时复制的容器.通俗的理解是当我们往一个容器添加元素的时候,不直 ...

  2. IDEA 使用Git clone项目【建议】

    1.在启动页点击Get from Version Control进行克隆,这样可以减少不必要克隆Bug. 2.项目目录保持一致(保证文件的正确性),父级目录不要有其它任何文件(防止文件名冲突) 3.通 ...

  3. chrome实现网页高清截屏(F12、shift+ctrl+p、capture)

    打开需要载屏的网页,在键盘上按下F12,出现以下界面 上图圈出的部分有可能会出现在浏览器下方,这并没有关系.此时按下 Ctrl + Shift + P(Mac 为 ⌘Command +⇧Shift + ...

  4. mysql数据库限制多次登录失败,限定用户重试时间

    前言 最近的项目开始进行安全测试,其中有一个安全问题是这样的. 应该增加用户登录失败处理功能,限制非法登录次数. 建议是增加mysql数据库的登陆失败的锁定功能. 相信大家也都会遇到这样的问题,在这里 ...

  5. springboot源码解析-管中窥豹系列之项目类型(二)

    一.前言 Springboot源码解析是一件大工程,逐行逐句的去研究代码,会很枯燥,也不容易坚持下去. 我们不追求大而全,而是试着每次去研究一个小知识点,最终聚沙成塔,这就是我们的springboot ...

  6. Java 8 之前的时间处理

    最近在自己瞎折腾,有一个需求是计算当前日期到指定日期有多少天,用于实现纪念日或倒计时的功能.查阅资料后发现Java 8之前的时间日期处理很是麻烦而且被频频吐槽,以至于后来在 Java 8 中推出了一个 ...

  7. 死磕以太坊源码分析之state

    死磕以太坊源码分析之state 配合以下代码进行阅读:https://github.com/blockchainGuide/ 希望读者在阅读过程中发现问题可以及时评论哦,大家一起进步. 源码目录 |- ...

  8. Docker一秒进阶

    tar包: 从tar包导入:docker load < xxxx.tar docker run -d -p 8080:80 --name [名字] -v `pwd`:/usr/share/ngi ...

  9. shelll中test命令的使用【转】

    Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值.字符和文件三个方面的测试. 数值测试 参数 说明 -eq 等于则为真 -ne 不等于则为真 -gt 大于则为真 -ge 大于等于 ...

  10. (解决)easypoi模板导出多个excel文件并压缩

    目录 easypoi版本--3.1.0 实现代码 后语 easypoi版本--3.1.0 实现代码 public void export(HttpServletResponse response, H ...