【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的学习笔记一直迟迟未记录,只引用了其他博主的博客链接占个位置,但被 ...
随机推荐
- 力扣(LeetCode)三个数的最大乘积 个人题解
给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积. 示例 1: 输入: [1,2,3] 输出: 6 示例 2: 输入: [1,2,3,4] 输出: 24 注意: 给定的整型数组长度 ...
- H5之外部浏览器唤起微信分享
最近在做一个手机站,要求点击分享可以直接打开微信分享出去.而不是jiathis,share分享这种的点击出来二维码.在网上看了很多,都说APP能唤起微信,手机网页实现不了.也找了很多都不能直接唤起微信 ...
- C++控制台闪回;编译器警告C4305,C4244
这是我以前解决问题时,收集在印象笔记里的内容,为了以后整理方便,把它转移至这里.以下内容,均来自微软官方网站相关. 问题:C++控制台闪回 解决办法: 1,在程序结尾添加system( ...
- python selenium框架的Xpath定位元素
我们工作中经常用到的定位方式有八大种:id name class_name tag_name link_text partial_link_text xpath css_selector 本篇内容主要 ...
- python3 之 变量作用域详解
作用域: 指命名空间可直接访问的python程序的文本区域,这里的 ‘可直接访问’ 意味着:对名称的引用(非限定),会尝试在命名空间中查找名称: L:local,局部作用域,即函数中定义的变量: E: ...
- 2019-11-3:渗透测试,基础学习,bypass类型笔记
等价字符 空格:%20,+,(),%0a,%09,%a0,%0b,%0c,%0d,/**/等 =:like,regexp,liker,<>,! =等 and:&& or:x ...
- java8 Optional优雅非空判断
java8 Optional优雅非空判断 import java.util.ArrayList;import java.util.List;import java.util.Optional; pub ...
- day 40 文本属性 常用css属性 定位
一. 浮动的特性 1.浮动的元素脱标 2.浮动的元素互相贴靠 3.浮动的元素由"字围"效果 4.收缩的效果 前提是标准文档流,margin的垂直方向会出现塌陷问题. 如果盒子居中: ...
- .Net Core3.0 WEB API 中使用FluentValidation验证,实现批量注入
为什么要使用FluentValidation 1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数 2.在领域模型中也应该验证,做好防御性的编程是一种好的习惯(其实 ...
- 一个有意义的Day类
早晨去单位的路上听到电台里在说“Everyday is a new chance to change your life”,正好最近在学Python类的使用方法,于是我编了一个关于Day的类,以供参考 ...