转载: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);
}

扩展了HttpEntityWrapperProgressEntityWrapper:

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()));
}
}

扩展了FilterOutputStreamCountingOutputStream:

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的更多相关文章

  1. Atitit 类库冲突解决方案  httpclient-4.5.2.jar

    Atitit 类库冲突解决方案  httpclient-4.5.2.jar 错误提示如下1 版本如下(client and selenium)2 解决流程2 挂载源码 (SSLConnectionSo ...

  2. httpclient4.3.6/httpcore-4.4自己封装的工具类

    引入jar包 httpclient4.3.6/httpcore-4.4 package com.develop.util; import java.io.IOException; import jav ...

  3. httpclient4.3 工具类

    httpclient4.3  java工具类. .. .因项目须要开发了一个工具类.正经常常使用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn. ...

  4. HttpClient4.0

    ****************************HttpClient4.0用法***************************** 1.初始化HttpParams,设置组件参数 //Ht ...

  5. [置顶] android网络通讯之HttpClient4不指定参数名发送Post

    在HttpClient4之前都是通过List<NameValuePair>键值对的形式来向服务器传递参数 ,在4.0版本中在加入了不指定参数名发送数据的形式,利用StringEntity来 ...

  6. HttpClient4的使用,模拟浏览器登陆新浪微博,发表微博和文字+图片微博

    HttpClient4,最原始的需求就是使用其来模拟浏览器想服务器发起http请求,当然,他的功能不止于此,但是我需要的就是这个功能而已,jdk也有其自带的类似的api:UrlConnection,效 ...

  7. HttpClient4.5 post请求xml到服务器

    1.加入HttpClient4.5和junit依赖包 <dependencies> <dependency> <groupId>org.apache.httpcom ...

  8. Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)

    先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...

  9. 使用HttpClient4.5实现HTTPS的双向认证

    说明:本文主要是在平时接口对接开发中遇到的为保证传输安全的情况特要求使用https进行交互的情况下,使用httpClient4.5版本对HTTPS的双向验证的  功能的实现    首先,老生常谈,文章 ...

  10. HttpClient4.5.2调用示例(转载+原创)

    操作HttpClient时的一个工具类,使用是HttpClient4.5.2 package com.xxxx.charactercheck.utils; import java.io.File; i ...

随机推荐

  1. 打印std::tuple的N总方式

    方式一:递归 + 类模板特化方式 template<typename Tuple, std::size_t N> struct tuple_printer { static void pr ...

  2. Python面试题之Python反射机制

    0x00 前言 def f1(): print('f1') def f2(): print('f2') def f3(): print('f3') def f4(): print('f4') a = ...

  3. kali rolling 配置网络

    一. 在文件系统里找到/etc/network下的interfaces文件,打开后可以看到eth0为dhcp,将其修改为如下形式: # This file describes the network ...

  4. vSphere SDK for Java - 从模板部署虚拟机并配置IP地址

    vSphere for Java类库:vijava    虚拟机配置类 package com.vmware.vcenter_event.VirtualMachine; import com.vmwa ...

  5. openwrt如何查看当前使用的硬件平台

    答:输入cat /tmp/sysinfo/board_name即可获取

  6. testng基础知识:注解的执行顺序

    1. 单类,无继承父子关系 code: public class basicTest { @BeforeSuite(alwaysRun = true) public void beforeSuite_ ...

  7. Android Studio开发学习 - 1. 添加Activity

    1. 项目上点右键,New -> Activity -> Blank Activity 这将生成Activity的 Layout.Class .和相关的配置信息(在AndroidManif ...

  8. centos配置yum源为中国镜像源

    有时候CentOS默认的yum源不一定是国内镜像,导致yum在线安装及更新速度不是很理想.这时候需要将yum源设置为国内镜像站点.国内主要开源的开源镜像站点应该是网易和阿里云了. 修改CentOS默认 ...

  9. Matrix_QP(A_2SeqSum)

    hdu_4686 题目大意:给出an,bn的递推,求ai*bi(i=0,1,--n-1)的和(an=a(n-1)*Ax+Ay, bn=b(n-1)*Bx+By, a0=A0, b0=B0, Ax,Bx ...

  10. 5.scala中的对象

    排版乱?请移步原文获得更好的阅读体验 1.单例对象 scala中没有静态类或者静态方法,都是通过object实现的,它表示某个类的单例对象.如object People是class People的单例 ...