【HttpClient】使用学习
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请求
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】使用学习的更多相关文章
- HttpClient研究学习总结
Http协议非常的重要,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人 ...
- Httpclient的学习(一)
1.名词解释 抓包: 抓包(packet capture)就是将网络传输发送与接收的数据包进行截获.重发.编辑.转存等操作,也用来检查网络安全.抓包也经常被用来进行数据截取等. Httpclient: ...
- HttpClient使用学习
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apac ...
- HttpClient&&RestTemplate学习
1. 什么是HttpClient HttpClient是Apache下面的子项目,可以提供高效的,最新的,功能丰富的支持HTTP协议的客户端编程工具包. 2. 为什么要学习HttpClient Htt ...
- android通过HttpClient与服务器JSON交互
通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; i ...
- HttpClient客户端网络编程——高可用、高并发
本文是HttpClient的学习博客,RestTemplate是基于HttpClient的封装,feign可基于HttpClient进行网络通信. 那么作为较底层的客户端网络编程框架,该怎么配置使其能 ...
- 在ASP dot Net Core MVC中用Controllers调用你的Asp dotnet Core Web API 实现CRUD到远程数据库中,构建你的分布式应用(附Git地址)
本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...
- 在Core环境下用WebRequest连接上远程的web Api 实现数据的简单CRUD(附Git地址)
本文所有的东西都是在dot Net Core 1.1环境+VS2017保证测试通过. 本文接着上次文章接着写的,不了解上篇文章的可能看着有点吃力.我尽量让大家都能看懂.这是上篇文章的连接http:// ...
- System.Net.Http
System.Net.Http DotNet菜园 占个位置^-^ 2018-11-10 09:55:00修改 这个HttpClient的学习笔记一直迟迟未记录,只引用了其他博主的博客链接占个位置,但被 ...
随机推荐
- systemd管理
systemd是为改进传统系统启动方式而退出的Linux系统管理工具,现已成为大多数Linux发行版的标准配置 systemd与系统初始化 Linux系统启动过程中,当内核启动并完成装载跟文件系统后, ...
- 用 GitBook 创建一本书
用 GitBook 创建一本书 Gitbook 首先是一个软件,它使用 Git 和 Markdown 来编排书本,如果你没有听过 Git 和 Markdown,那么 gitbook 可能不适合你直接入 ...
- js-程序结构
程序结构: 1.顺序结构(主体结构):自上而下,逐行实行: 2.分支(选择)结构:if语句,if…else, if…else if…else,switch; 3.循环结构:重复某些代码: 分支 ...
- MySQL 5.7 - 通过 BINLOG 恢复数据
日常开发,运维中,经常会出现误删数据的情况.误删数据的类型大致可分为以下几类: 使用 delete 误删行 使用 drop table 或 truncate table 误删表 使用 drop dat ...
- php中static关键字的理解
函数内的static变量 static静态变量的理解 静态变量 类型说明符是static. 静态变量属于静态存储方式,其存储空间为内存中的静态数据区(在 静态存储区内分配存储单元),该区域中的数据在整 ...
- 胜利点组——“萌猿填词”微信小程序评价
此作业要求参见https://edu.cnblogs.com/campus/nenu/2019fall/homework/9860 1.根据(不限于)NABCD评论作品的选题; (1).你的创意解决了 ...
- 20190926-2 选题 Scrum立会报告+燃尽图05
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2019fall/homework/8678 一.小组情况组长:迟俊文组员:宋晓丽 梁梦瑶 韩昊 刘信鹏队名:扛 ...
- java集合讲解
java集合讲解 1.概述 集合类的顶级接口是Iterable,Collection继承了Iterable接口 常用的集合主要有 3 类,Set,List,Queue,他们都是接口,都继于Collec ...
- vue 做一个简单的TodoList
目录结构 index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"&g ...
- 数据降维-PCA主成分分析
1.什么是PCA? PCA(Principal Component Analysis),即主成分分析方法,是一种使用最广泛的数据降维算法.PCA的主要思想是将n维特征映射到k维上,这k维是全新的正交特 ...