下面是一个通过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、上手真实开发及转行程序员的建议

    前路漫漫,吾将上下而求索! 最近有时在知乎上逛逛,发现很多人对自学编程及转行程序员有困惑.我是在25岁读研时转程序员,正赶上好时候(中国云计算刚刚起步及移动互联网正红的阶段),同时又走了不少弯路,因此 ...

  2. 理解Tomcat工作原理

    WEB服务器 只要Web上的Server都叫Web Server,但是大家分工不同,解决的问题也不同,所以根据Web Server提供的功能,每个Web Server的名字也会不一样. 按功能分类,W ...

  3. SpringBoot 的多数据源配置

    最近在项目开发中,需要为一个使用 MySQL 数据库的 SpringBoot 项目,新添加一个 PLSQL 数据库数据源,那么就需要进行 SpringBoot 的多数据源开发.代码很简单,下面是实现的 ...

  4. SpringMVC+JPA+SpringData配置

    <properties>   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  ...

  5. 前端网页打印插件print.js(可导出pdf)

    在前端开发中,想打印当前网页的指定区域内容,或将网页导出为多页的PDF,可以借助print.js实现,该插件轻量.简单.手动引入.不依赖其他库.示范项目github:https://github.co ...

  6. git pull 和git fetch的区别

    git pull 是上下文环境敏感的,它会把所有的提交自动给你合并到当前分支当中,没有复查的过程 而git fetch只是把拉去的提交存储到本地仓库中,真正合并到主分支中需要使用merage head ...

  7. redis加锁的几种实现

    redis加锁的几种实现 2017/09/21 1. redis加锁分类 redis能用的的加锁命令分表是INCR.SETNX.SET 2. 第一种锁命令INCR 这种加锁的思路是, key 不存在, ...

  8. HashSet/HashMap 存取值的过程

    HashSet与HashMap的关系: (1)HashSet底层用的是HashMap来实现的 (2)这个HashMap的key就是放进HashSet中的对象,value就是一个Object类型的对象 ...

  9. Spring-构造注入&注解注入&代理模式&AOP

    1.   课程介绍 1.  依赖注入;(掌握) 2.  XML自动注入;(掌握) 3.  全注解配置;(掌握) 4.  代理模式;(掌握) 5.  AOP;(掌握) 依赖注入;(掌握) 2.1.  构 ...

  10. 第二章节 BJROBOT IMU 自动校正 【ROS全开源阿克曼转向智能网联无人驾驶车】

    1.把小车平放在地板上,用资料里的虚拟机,打开一个终端 ssh 过去主控端启动roslaunch znjrobot bringup.launch . 2.再打开一个终端,ssh 过去主控端,在 ~/c ...