Post with HttpClient
Apache HttpClient是Java中经常使用的Http Client,总结下HttpClient4中经常使用的post请求用法。
1 Basic Post
使用2个参数进行post请求:
@Test
public void whenPostRequestUsingHttpClient_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com"); List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "John"));
params.add(new BasicNameValuePair("password", "pass"));
httpPost.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
2 POST with Authorization
使用Post进行Basic Authentication credentials验证:
@Test
public void whenPostRequestWithAuthorizationUsingHttpClient_thenCorrect()
throws ClientProtocolException, IOException, AuthenticationException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com"); httpPost.setEntity(new StringEntity("test post"));
UsernamePasswordCredentials creds =
new UsernamePasswordCredentials("John", "pass");
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null)); CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
3 Post with JSON
使用JSON body进行post请求:
@Test
public void whenPostJsonUsingHttpClient_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com"); String json = "{"id":1,"name":"John"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json"); CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
4 Post with HttpClient Fluent API
使用Request进行post请求:
@Test
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect()
throws ClientProtocolException, IOException {
HttpResponse response =
Request.Post("http://www.example.com").bodyForm(
Form.form().add("username", "John").add("password", "pass").build())
.execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
5 Post Multipart Request
Post一个Multipart Request:
@Test
public void whenSendMultipartRequestUsingHttpClient_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", "John");
builder.addTextBody("password", "pass");
builder.addBinaryBody("file", new File("test.txt"),
ContentType.APPLICATION_OCTET_STREAM, "file.ext"); HttpEntity multipart = builder.build();
httpPost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
6 Upload a File using HttpClient
使用一个Post请求上传一个文件:
@Test
public void whenUploadFileUsingHttpClient_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("test.txt"),
ContentType.APPLICATION_OCTET_STREAM, "file.ext");
HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
7 Get File Upload Progress
使用HttpClient获取文件上传的进度。扩展HttpEntityWrapper 获取进度。
上传代码:
@Test
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect()
throws ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com"); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("test.txt"),
ContentType.APPLICATION_OCTET_STREAM, "file.ext");
HttpEntity multipart = builder.build(); ProgressEntityWrapper.ProgressListener pListener =
new ProgressEntityWrapper.ProgressListener() {
@Override
public void progress(float percentage) {
assertFalse(Float.compare(percentage, 100) > 0);
}
}; httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
观察上传进度接口:
public static interface ProgressListener {
void progress(float percentage);
}
扩展了HttpEntityWrapper的ProgressEntityWrapper:
public class ProgressEntityWrapper extends HttpEntityWrapper {
private ProgressListener listener; public ProgressEntityWrapper(HttpEntity entity,
ProgressListener listener) {
super(entity);
this.listener = listener;
} @Override
public void writeTo(OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream,
listener, getContentLength()));
}
}
扩展了FilterOutputStream的CountingOutputStream:
public static class CountingOutputStream extends FilterOutputStream {
private ProgressListener listener;
private long transferred;
private long totalBytes; public CountingOutputStream(
OutputStream out, ProgressListener listener, long totalBytes) {
super(out);
this.listener = listener;
transferred = 0;
this.totalBytes = totalBytes;
} @Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
transferred += len;
listener.progress(getCurrentProgress());
} @Override
public void write(int b) throws IOException {
out.write(b);
transferred++;
listener.progress(getCurrentProgress());
} private float getCurrentProgress() {
return ((float) transferred / totalBytes) * 100;
}
}
总结
简单举例说明如何使用Apache HttpClient 4进行各种post请求。做个笔记。
Post with HttpClient的更多相关文章
- HttpClient的替代者 - RestTemplate
需要的包 ,除了Spring的基础包外还用到json的包,这里的数据传输使用json格式 客户端和服务端都用到一下的包 <!-- Spring --> <dependency> ...
- 关于微软HttpClient使用,避免踩坑
最近公司对于WebApi的场景使用也越来越加大了,随之而来就是Api的客户端工具我们使用哪个?我们最常用的估计就是HttpClient,在微软类库中命名空间地址:System.Net.Http,是一个 ...
- 使用HttpClient的优解
新工作入职不满半周,目前仍然还在交接工作,适应环境当中,笔者不得不说看别人的源码实在是令人痛苦.所幸今天终于将大部分工作流畅地看了一遍,接下来就是熟悉框架技术的阶段了. 也正是在看源码的过程当中,有一 ...
- Java的异步HttpClient
上篇提到了高性能处理的关键是异步,而我们当中许多人依旧在使用同步模式的HttpClient访问第三方Web资源,我认为原因之一是:异步的HttpClient诞生较晚,许多人不知道:另外也可能是大多数W ...
- 揭秘Windows10 UWP中的httpclient接口[2]
阅读目录: 概述 如何选择 System.Net.Http Windows.Web.Http HTTP的常用功能 修改http头部 设置超时 使用身份验证凭据 使用客户端证书 cookie处理 概述 ...
- C#中HttpClient使用注意:预热与长连接
最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...
- HttpClient调用webApi时注意的小问题
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...
- HttpClient相关
HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...
- Atitit.http httpclient实践java c# .net php attilax总结
Atitit.http httpclient实践java c# .net php attilax总结 1. Navtree>> net .http1 2. Httpclient理论1 2. ...
- 使用httpclient发送get或post请求
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...
随机推荐
- LR破解版录制手机脚本(一)模拟器录制
最近在网上听到好多童鞋都在问如何用LR做手机性能测试,恰好自己对这方面也挺感兴趣,经过查阅很多资料,形成此文档以做备注~!如果有感觉我写的不对的地方,敬请指正,谢谢~! 其实自从LR12出来之 ...
- mybatis-generator运行命令
java -jar mybatis-generator-core-x.x.x.jar -configfile generatorConfig.xml -overwrite
- http执行过程分析
执行过程: 1.用户在浏览器(客户端)里输入或者点击一个网址链接: 2.浏览器通过网址域名查找ip地址.DNS查找方式是通过浏览器缓存(会记录DNS记录)→系统缓存→TCP/IP参数中设置的首选DNS ...
- 【辅助远程连接,可穿防火墙、NAT】一次 TeamViewer 的安装与测试
背景: 应课程老师要求帮助某化学老师维修机器(高性能电脑),并解决老师的若干问题,在解决硬件问题(上网问题:多个网络接口)之后,化学老师提出需要远程链接到该机器,试询问之前如何实现,化学老师推荐Tea ...
- Django基础,Day4 - views 详解
在Django中,网页和其他内容是通过视图传递的.每个视图由一个简单的Python函数表示,Django将通过检查请求的URL(准确地说,是域名后面的部分URL)来选择一个视图. 例如,用户在浏览器中 ...
- Python
语法 #!/usr/bin/python 注释:# 编码:# -*- coding: UTF-8 -*- 缩进 运算符 算数运算符 + 加 - 两个对象相加 a + b 输出结果 30 - 减 - 得 ...
- Money, save or spend, this is a problem .
Win a lottery? Had a great hand at the casino? Did fortune shine upon you in the stock market? 彩票中了大 ...
- C语言: 运算符,printf,scanf的用法
运算符/的运算结果和运算对象的数据类型有关,两个数都是in,则商就是int,取整数部分:被除数和除数中只要有一个或两个都是浮点型数据,则商也是浮点型,不去掉小数部分如:16/5 == 3:16/5.0 ...
- 用Model-View-ViewModel构建iOS App
如果你已经开发一段时间的iOS应用,你一定听说过Model-View-Controller,即MVC.MVC是构建iOS App的标准模式.然而,最近我已经越来越厌倦MVC的一些缺点.在本文,我将重温 ...
- JSP的9大内置对象
1.概述 JSP的这9个内置对象,都是servlet API实例,即在JSP页面内部,可以直接使用; ps:顺便说下JSP的4大范围: JSP的四种范围,分别为page.request.session ...