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 ...
随机推荐
- Django小练习
1.获取系统所有Url from django.urls.resolvers import RegexURLPattern #定义函数 def get_all_url(patterns, prev, ...
- Python3 安装第三方包
打开cmd(切记是cmd,不是Python3.6那个敲代码环境)输入 pip3 install numpy 即可(安装numpy包)
- 转载:逻辑回归的python实现
转载自:http://blog.csdn.net/zouxy09/article/details/20319673 一.逻辑回归(LogisticRegression) Logistic regres ...
- go panic recover 异常处理
Go语言追求简洁优雅,所以,Go语言不支持传统的 try…catch…finally 这种异常,因为Go语言的设计者们认为,将异常与控制结构混在一起会很容易使得代码变得混乱.因为开发者很容易滥用异常, ...
- thrift使用上面的一些坑
https://blog.csdn.net/andylau00j/article/details/53912485
- 20145335郝昊《java程序设计》第1次实验报告
2014535郝昊<java程序设计>实验1实验报告 实验名称 利用java语言实现凯撒密码,并运行测试. 实验内容 用java语言实现凯撒密码,凯撒密码是一种代替的移位密码,它将明文加密 ...
- 20162314 Sortingtest-work after class
20162314 Sortingtest-work after class Content Data : 90 8 7 56 123 235 9 1 653. Use JDB or IDEA to t ...
- 置顶,置低实现与window.scroll
//置顶,置低实现 $('#updown .up').click(function(){$('html,body').animate({scrollTop: '0px'}, 300);}); $('# ...
- Eye Protection FAQ
Q: Why does smart protection not work? A: Please make sure the checkbox "Eye Protection" i ...
- jsp中获取list长度
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ tag ...