【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)移除链表元素 个人题解
删除链表中等于给定值 val 的所有节点. 这题粗看并不困难,链表的特性让移除元素特别轻松,只用遇到和val相同的就跳过,将指针指向下一个,以此类推. 但是,一个比较麻烦的问题是,当链表所有元素都和v ...
- 关于element-ui级联菜单(城市三级联动菜单)和回显问题
https://segmentfault.com/a/1190000020458087 这是我写的,可以去看看,希望对你们有帮助!!!
- SpringBoot 源码解析 (九)----- Spring Boot的核心能力 - 整合Mybatis
本篇我们在SpringBoot中整合Mybatis这个orm框架,毕竟分析一下其自动配置的源码,我们先来回顾一下以前Spring中是如何整合Mybatis的,大家可以看看我这篇文章Mybaits 源码 ...
- 元数据管理的重要性 - xms
什么是元数据?引用百科的描述就是:元数据(Metadata),又称中介数据.中继数据,为描述数据的数据(data about data),主要是描述数据属性(property)的信息: 看起来有点抽象 ...
- Acquistion Location Confidence for accurate object detection
Acquistion Location Confidence for accurate object detection 本论文主要是解决一下两个问题: 1.分类得分高的预测框与IOU不匹配,(我猜应 ...
- [CSS七分钟系列]都1902年了,还不知道用margin:auto给flex容器内元素分组?
最近看到几篇博文讲解margin:auto在flex容器中的使用,可惜的是大多讲解都浮于页面表现,没深究其中的作用机理,本文在此浅薄对其表现机理做简单探讨. 引子 日常业务迭代过程中,flex已经是前 ...
- SpringMVC配置了拦截器(interceptors)却显示不出css、js样式的解决办法
首先因为在web.xml里面配置了 <filter-mapping> <filter-name>characterEncodingFilter</filter-name& ...
- fastjson 1.2.24-基于JdbcRowSetImpl的PoC构造与分析
前言: 基于fastjson的第一种payload是基于templatesImpl的方式,但是这种方式要求Feature.SupportNonPublicField才能打开非公有属性的反序列化处理,是 ...
- C# VS2019 WebService创建与发布,并部署到Windows Server 2012R
前言 上一次数据库灾备和性能优化后,数据库专家建议,在不扩容的情况下,客户端不能再频繁的扫描数据库了!一句惊醒梦中人,因为我也发现数据库越来越卡了,自从上个项目上线后,就出现了这个情况.后来分析其原因 ...
- 理解Java对象序列化【转】
原文链接:http://www.blogjava.net/jiangshachina/archive/2012/02/13/369898.html 关于Java序列化的文章早已是汗牛充栋了,本文是 ...