Post with HttpClient4
转载:http://www.cnblogs.com/luxiaoxun/p/6165237.html
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 HttpClient4的更多相关文章
- Atitit 类库冲突解决方案 httpclient-4.5.2.jar
Atitit 类库冲突解决方案 httpclient-4.5.2.jar 错误提示如下1 版本如下(client and selenium)2 解决流程2 挂载源码 (SSLConnectionSo ...
- httpclient4.3.6/httpcore-4.4自己封装的工具类
引入jar包 httpclient4.3.6/httpcore-4.4 package com.develop.util; import java.io.IOException; import jav ...
- httpclient4.3 工具类
httpclient4.3 java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...
- HttpClient4.0
****************************HttpClient4.0用法***************************** 1.初始化HttpParams,设置组件参数 //Ht ...
- [置顶] android网络通讯之HttpClient4不指定参数名发送Post
在HttpClient4之前都是通过List<NameValuePair>键值对的形式来向服务器传递参数 ,在4.0版本中在加入了不指定参数名发送数据的形式,利用StringEntity来 ...
- HttpClient4的使用,模拟浏览器登陆新浪微博,发表微博和文字+图片微博
HttpClient4,最原始的需求就是使用其来模拟浏览器想服务器发起http请求,当然,他的功能不止于此,但是我需要的就是这个功能而已,jdk也有其自带的类似的api:UrlConnection,效 ...
- HttpClient4.5 post请求xml到服务器
1.加入HttpClient4.5和junit依赖包 <dependencies> <dependency> <groupId>org.apache.httpcom ...
- Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...
- 使用HttpClient4.5实现HTTPS的双向认证
说明:本文主要是在平时接口对接开发中遇到的为保证传输安全的情况特要求使用https进行交互的情况下,使用httpClient4.5版本对HTTPS的双向验证的 功能的实现 首先,老生常谈,文章 ...
- HttpClient4.5.2调用示例(转载+原创)
操作HttpClient时的一个工具类,使用是HttpClient4.5.2 package com.xxxx.charactercheck.utils; import java.io.File; i ...
随机推荐
- python的数据类型的有序无序
列表有序可变 字典无序不可变 元组不可变 集合无序不可变 数字不可变 字符串不可变
- Tfs更新 TfsConfig
Start TfsJobAgent TfsServiceControl unquiesce 更新serviving状态 TfsConfig diagnose /scope:updates TfsCon ...
- Winter-2-STL-E Andy's First Dictionary 解题报告及测试数据
use stringstream Time Limit:3000MS Memory Limit:0KB Description Andy, 8, has a dream - he wants ...
- windows使用IPC和文件共享
远程访问windows资源有很多方式,如果给自己用可以使用ipc或开启共享设置只共享给特定用户.如果给所有人用,可以开启everyone共享和guest账户 { "远程获取Windows资源 ...
- Python3.x:python: extend (扩展) 与 append (追加) 的区别
Python3.x:python: extend (扩展) 与 append (追加) 的区别 1,区别: append() 方法向列表的尾部添加一个新的元素.只接受一个参数: extend()方法只 ...
- 20145328 《Java程序设计》实验二实验报告
20145328 <Java程序设计>实验二实验报告 实验名称 Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 ...
- git分支合并脚本
为什么要写这个脚本 工作中经常会有合并分支的操作,一开始也不以为然,后来发现如果更新频繁的话,根本就停不下来,昨天上午正好有空,就完成了下面的这个初版 可能存在的问题 一般的应用场景都是:从maste ...
- PHP设计模式(六): 单例模式
- cmd中如何查看环境变量
查看所有环境变量 set 查看某一个环境变量 C:\WINDOWS\system32>set no_proxyNO_PROXY=localhost,127.0.0.1,172.31.212.14 ...
- Azure Active Directory配置java应用的单点登录
下载应用:https://github.com/Azure-Samples/active-directory-java-webapp-openidconnect(普通项目,集成了特殊配置接入微软的注册 ...