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 ...
随机推荐
- Godaddy域名因为whois信息虚假被暂时关闭
如果你收到来自 Godadddy 通过 invalidwhois@godaddy.com 发出的标题为如下内容的邮件: [Incident ID: xxxx] xxxx - DS Invalid Wh ...
- 20145316 《Java程序设计》第8周学习总结
20145316 <Java程序设计>第8周学习总结 教材学习内容总结 NIO&NIO2 NIO使用频道(channel)衔接数据节点,对数据区的标记提供了clear(),rewi ...
- ABP官方文档翻译 1.4 启动配置
启动配置 配置ABP 替换内置服务 配置模块 创建模块配置 ABP提供了基础设施和模型在启动的时候对它及模块进行配置. 配置ABP 在模块的PreInitialize事件中配置ABP.示例配置如下: ...
- WebSocket安卓客户端实现详解(一)–连接建立与重连
http://blog.csdn.net/zly921112/article/details/72973054 前言 这里特别说明下因为WebSocket服务端是公司线上项目所以这里url和具体协议我 ...
- debug教程
名称 解释 格式 a (Assemble) 逐行汇编 a [address] c (Compare) 比较两内存块 c range address d (Dump) 内存16进制显示 d [addre ...
- kali安装机场v2ray客户端
为了方便查找资料,之前安装的ssr在kali上面,感觉速度不怎么快,相比windows和android上慢很多,所以打算在kali上面装个机场试试,看官方介绍说机场比ssr速度更快,下面是安装步骤: ...
- linux 第三周
linux内核目录结构 arch目录包括了所有和体系结构相关的核心代码.它下面的每一个子目录都代表一种Linux支持的体系结构,例如i386就是Intel CPU及与之相兼容体系结构的子目录.PC机一 ...
- android ramdisk
android ramdisk 1.android文件系统的结构android源码编译后得到system.img,ramdisk.img,userdata.img映像文件.其中, ramdisk.im ...
- Material Design学习之 Camera
转载请注明出处:王亟亟的大牛之路 年后第一篇,自从来了某司产量骤减,这里批评下自己,这一篇的素材来源于老牌Material Design控件写手afollestad的 https://github.c ...
- 混合开发的大趋势之一React Native手势行为那些事
转载请注明出处:王亟亟的大牛之路 最近项目部分模块重构,事情有点多,学习进度有所延缓,外加一直在吸毒(wow你懂的),导致好多天没发问了,其实这部分知识月头就想写了,一直没补. 话不多说先安利:htt ...