HttpClient使用学习

HttpClient Tutorial:http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/index.html

HttpClient是Apache HttpComponents中的一部分,下载地址:http://hc.apache.org/

转载:https://www.cnblogs.com/yangchongxing/p/9191073.html

目录:

===========================================================================

1、简单的Get请求

2、文件上传

3、请求配置

4、拦截器

5、从链接管理获得链接

6、链接管理池

7、连接保持活着策略

8、SSL使用实例PKCS12证书

===========================================================================

1、简单的Get请求

package core;

import java.io.InputStream;
import java.nio.charset.Charset; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; public class Test { public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
int code = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == code) {
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
try {
Charset charset = Charset.forName("UTF-8");
int len = 0;
byte[] buf = new byte[2048];
while( (len = inputStream.read(buf)) != -1 ) {
System.out.print(new String(buf, 0, len, charset));
}
} finally {
inputStream.close();
}
}
} finally {
response.close();
}
}
} }

 2、文件上传

package com.yuanxingyuan.common.util;

import java.io.File;
import java.io.IOException; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; /**
* http client工具类
* @author 杨崇兴
*
*/
public class HttpClientUtil { public static String postFile(String url, File file) {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("file", file);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(multipartEntityBuilder.build());
try {
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
}
return result;
} public static void main(String[] args) {
String result = HttpClientUtil.postFile("http://localhost:8080/upload/image",new File("E:/wx/image.jpg"));
System.out.println(result);
}
}

服务端使用servlet3.0

import java.io.IOException;
import java.util.Collection; import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part; import org.apache.catalina.core.ApplicationPart; /**
* Servlet implementation class Upload
*/
@WebServlet("/image")
@MultipartConfig
public class Upload extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public Upload() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Collection<Part> parts = request.getParts();
if (parts != null) {
for(Part part : parts){
ApplicationPart ap= (ApplicationPart) part;
String name = ap.getSubmittedFileName();
part.write("E:/"+name);
System.out.println("upload ok. " + name);
}
}
} }
package httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List; import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; public class Main {
public static void main(String[] args) throws ClientProtocolException, IOException {
//https://www.baidu.com/s?wd=%E8%A5%BF%E5%AE%89
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name","西安"));
HttpPost post = new HttpPost("http://www.baidu.com/s?wd=西安");
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params);
post.setEntity(urlEncodedFormEntity);
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while( (line = reader.readLine()) != null ) {
System.out.println(line);
}
reader.close();
response.close();
client.close();
}
}

3、请求配置

HttpGet httpGet = new HttpGet("http://localhost/demo/api/test/3");
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
httpGet.setConfig(config);

4、拦截器

CloseableHttpClient httpClient = HttpClients.custom()
.addInterceptorLast(new HttpRequestInterceptor(){
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
String count = (String) context.getAttribute("count");
request.addHeader("count", count);
}
}).build();
HttpGet httpGet = new HttpGet("http://localhost/demo/test/3");
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build();
httpGet.setConfig(config); HttpClientContext context = HttpClientContext.create();
context.setAttribute("count", "111"); CloseableHttpResponse httpResponse = httpClient.execute(httpGet, context);
int code = httpResponse.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == code) {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
Charset charset = Charset.forName("UTF-8");
System.out.println(EntityUtils.toString(entity, charset));
}
}
httpResponse.close();
httpClient.close();

HttpClientBuilder addInterceptorFirst(final HttpResponseInterceptor itcp)
HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp)
HttpClientBuilder addInterceptorLast(final HttpResponseInterceptor itcp)
HttpClientBuilder addInterceptorLast(final HttpRequestInterceptor itcp)

添加四种类型的拦截器

5、从链接管理获得链接

HttpClientContext context = HttpClientContext.create();
HttpClientConnectionManager manager = new BasicHttpClientConnectionManager();
HttpRoute route = new HttpRoute(new HttpHost("119.23.107.129", 80));
ConnectionRequest request = manager.requestConnection(route, null);
HttpClientConnection conn = request.get(10, TimeUnit.SECONDS);
if (conn.isOpen()) {
manager.connect(conn, route, 1000, context);
manager.routeComplete(conn, route, context);
manager.releaseConnection(conn, null, 1, TimeUnit.MINUTES);
}

6、链接管理池

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
// Increase max connections for localhost:80 to 50
HttpHost localhost = new HttpHost("locahost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();

7、连接保持活着策略

ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch(NumberFormatException ignore) {
}
}
}
HttpHost target = (HttpHost) context.getAttribute(
HttpClientContext.HTTP_TARGET_HOST);
if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
// Keep alive for 5 seconds only
return 5 * 1000;
} else {
// otherwise keep alive for 30 seconds
return 30 * 1000;
}
}};
CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(myStrategy).build();

8、SSL使用实例PKCS12证书

url 请求地址

xmlObj 发送xml数据

certKey 证书密钥

certPath 证书文件地址PKCS12证书

@SuppressWarnings("unchecked")
public static Map<String, String> httpsPostRequestCert(String url, String xmlObj, String certKey, String certPath) {
Map<String, String> wxmap = new HashMap<String, String>();
try {
// 指定读取证书格式为PKCS12
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// 读取本机存放的PKCS12证书文件
FileInputStream instream = new FileInputStream(new File(certPath));
// 指定PKCS12的密码(商户ID)
keyStore.load(instream, certKey.toCharArray());
instream.close(); SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certKey.toCharArray()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); HttpPost httpPost = new HttpPost(url);
// 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(new StringEntity(xmlObj, "UTF-8"));
// 根据默认超时限制初始化requestConfig
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(30000).build();
// 设置请求器的配置
httpPost.setConfig(requestConfig); HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
//转换为Map
InputStream inputStream = entity.getContent();
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for (Element e : elementList) {
wxmap.put(e.getName(), e.getText());
}
} catch (Exception e) {
wxmap.put("return_msg", e.getMessage());
}
return wxmap;
}

【HttpClient】使用学习的更多相关文章

  1. HttpClient研究学习总结

    Http协议非常的重要,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人 ...

  2. Httpclient的学习(一)

    1.名词解释 抓包: 抓包(packet capture)就是将网络传输发送与接收的数据包进行截获.重发.编辑.转存等操作,也用来检查网络安全.抓包也经常被用来进行数据截取等. Httpclient: ...

  3. HttpClient使用学习

    import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apac ...

  4. HttpClient&&RestTemplate学习

    1. 什么是HttpClient HttpClient是Apache下面的子项目,可以提供高效的,最新的,功能丰富的支持HTTP协议的客户端编程工具包. 2. 为什么要学习HttpClient Htt ...

  5. android通过HttpClient与服务器JSON交互

    通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; i ...

  6. HttpClient客户端网络编程——高可用、高并发

    本文是HttpClient的学习博客,RestTemplate是基于HttpClient的封装,feign可基于HttpClient进行网络通信. 那么作为较底层的客户端网络编程框架,该怎么配置使其能 ...

  7. 在ASP dot Net Core MVC中用Controllers调用你的Asp dotnet Core Web API 实现CRUD到远程数据库中,构建你的分布式应用(附Git地址)

    本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...

  8. 在Core环境下用WebRequest连接上远程的web Api 实现数据的简单CRUD(附Git地址)

    本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...

  9. System.Net.Http

    System.Net.Http DotNet菜园 占个位置^-^ 2018-11-10 09:55:00修改 这个HttpClient的学习笔记一直迟迟未记录,只引用了其他博主的博客链接占个位置,但被 ...

随机推荐

  1. 【故障公告】数据库服务器 CPU 近 100% 引发的故障(源于 .NET Core 3.0 的一个 bug)

    非常抱歉,这次故障给您带来麻烦了,请您谅解. 今天早上 10:54 左右,我们所使用的数据库服务(阿里云 RDS 实例 SQL Server 2016 标准版)CPU 突然飙升至 90% 以上,应用日 ...

  2. UML:类图关系总结

    UML类图几种关系的总结,泛化 = 实现 > 组合 > 聚合 > 关联 > 依赖在UML类图中,常见的有以下几种关系: 泛化(Generalization), 实现(Reali ...

  3. RevitAPI 隐藏UI读取Revit文件

    1.1. 新建一个控制台项目 1.2. 添加Revit API引用 我们找到revit安装目录下的这两个DLL添加到项目引用中 RevitNET.dll RevitAPI.dll 修改属性:复制本地: ...

  4. Curl elasticsearch

    1. 查看cluster state curl localhost:9200/_cluster/health?pretty Or curl localhost:9200/_cluster/health ...

  5. C++学习第二天(打卡)

    C++ new 可以很方便的 分配一段内存. 比如 int *test= new int ; int n; cin>>n; int * test =new int [n]; 可以实现动态分 ...

  6. css居中布局的几种方式

    一.水平居中 若是行内元素,则直接给其父元素设置text-align: center即可 若是块级元素,则直接给该元素设置margin: 0 auto即可 若子元素包含浮动元素,则给父元素设置widt ...

  7. Spring Boot整合Mybatis报错InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    Spring Boot整合Mybatis时一直报错 后来发现原来主配置类上的MapperScan导错了包 由于我使用了通用Mapper,所以应该导入通用mapper这个包

  8. 插入节点(appendChild())

    appendChild():方法将给元素节点追加一个子节点: reference = element.appendChild(newChild); 如上所示,给定节点newChild将成为给定元素节点 ...

  9. MySQL5.6.36 自动化安装脚本

    背景 很好的朋友邱启明同学,擅长MySQL,目前任职某大型互联网业MySQL DBA,要来一套MySQL自动安装的Shell脚本,贴出来保存一些. 此版本为 MySQL 5.6.365 ###### ...

  10. java 运算符&表达式

    1. java中,模运算符%可以获取整数除法的余数,同样适用于浮点类型数据.double y = 23.56; y%5;(即y mod 5 =3.56) [c/c++中,要求%两侧均为整数数据.] 2 ...