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 协议最新的版本和建 ...
随机推荐
- 个人对B/S项目的一些理解(一)
以下是我自工作以来,结合对C/S项目的认知,对B/S项目的一些理解. 如有不足或者错误,请各位指正. B/S browser/server ----对于这两个软件的个人看法 本质上,也是两个软 ...
- web主题公园版权信息破解:script.js加密文件
很多人会使用web主题公园网站的免费worldpress主题,但它的主题又都被加了版权信息,故意让人找不到版权信息的修改位置. 你如果去footer.php里面删除版权信息(技术支持:web主题公园) ...
- JS 的实例和对象的区别
对于传统的OOP思想,JS的语法确实比较难搞,其中之一就是实例和对象的区别. 什么是实例? 实例是类的具体化产品. JS语法没有类这个概念(当然ES6引用了类这个概念).只能通过构造函数来创建类,例如 ...
- 再谈 Mysql解决中文乱码
一是要把数据库服务器的字符集设置为 utf8. 数据库的字符集会跟服务器的字符集一起变化, 也会变成 utf8: 在/etc/my.cnf中, 的 [mysqld]中, 设置 character-se ...
- 5 Hbase
# 大纲: * 认识 HBase * HBase 架构 * HBase读写流程 定义: * HBase是一个高可靠性.高性能.面向列.可伸缩的分布式存储系统,利用Hbase 技术可在廉价PC S ...
- laravel强大功能路由初探(二)
目标当然是先输出helloworld 配置hosts文件和apache下的httpd-vhosts.conf, hosts:127.0.0.1 www.blog.com httpd-vhosts.c ...
- Sicily 1151: 简单的马周游问题(DFS)
这道题嘛,直接使用DFS搜索,然后莫名其妙地AC了.后来看了题解,说是move的顺序不同的话可能会导致超时,这时便需要剪枝,真是有趣.原来自己是误打误撞AC了,hhh.题解还有另一种解法是先把一条完整 ...
- [BZOJ3729]Gty的游戏
[BZOJ3729]Gty的游戏 试题描述 某一天gty在与他的妹子玩游戏.妹子提出一个游戏,给定一棵有根树,每个节点有一些石子,每次可以将不多于L的石子移动到父节点,询问将某个节点的子树中的石子移动 ...
- Buddy内存分配算法
Buddy(伙伴的定义): 这里给出伙伴的概念,满足以下三个条件的称为伙伴:1)两个块大小相同:2)两个块地址连续:3)两个块必须是同一个大块中分离出来的: Buddy算法的优缺点: 1)尽管伙伴内存 ...
- 在Oracle中恢复被DROP掉的表
在Oracle中可能不小心会DROP掉一个表,如果没有定期做备份的话,将会带来很大的麻烦.如果有的情况下,每天的数据都很重要,而定期备份的周期又稍长,情况恐怕也不容乐观!以前只知道Windows有个回 ...