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

扩展了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请求。做个笔记。



    本文转自阿凡卢博客园博客,原文链接:http://www.cnblogs.com/luxiaoxun/p/6165237.html,如需转载请自行联系原作者

相关文章
|
数据可视化 应用服务中间件 数据安全/隐私保护
轻量应用服务器部署k3s,并搭建可视化高性能网关 apisix
k3s低资源占用集群,apisix 可视化高性能网关。小白教程
2214 0
|
编解码 Linux 计算机视觉
RoboMaster 视觉 摄像头教程
这篇文章是RoboMaster视觉教程的一部分,介绍了摄像头的参数选择、曝光和Gamma矫正技术,以及如何在Linux环境下使用OpenCV库来配置和操作摄像头,以满足高速视觉处理的需求。
RoboMaster 视觉 摄像头教程
|
9月前
|
数据库
【YashanDB知识库】服务器重启后启动yasom和yasagent进程时有告警
本文介绍了YashanDB在特定场景下的问题分析与解决方法。当使用yasboot重启数据库后,yasom和yasagent进程虽启动成功但出现告警,原因是缺少libnsl.so.1库文件或环境变量配置错误。解决步骤包括:检查系统中是否存在该库文件,若不存在则根据操作系统类型安装(有外网时通过yum或apt,无外网时创建符号链接),若存在则调整环境变量配置,并重新启动相关进程验证问题是否解决。
|
Web App开发 存储
常见抓包工具配置抓取HTTPS
常见抓包工具配置抓取HTTPS
1668 1
|
Web App开发 XML 安全
海康威视iVMS综合安防系统任意文件上传漏洞
海康威视iVMS综合安防系统存在任意文件上传漏洞 ,攻击者可通过构造特定Payload实施对目标的攻击。
1354 1
|
算法
基于DSP的音频信号降噪技术
基于DSP的音频信号降噪技术
646 4
如何去掉字符串中文括号及其内部的内容三种方式
如何去掉字符串中文括号及其内部的内容三种方式
752 0
|
算法 固态存储 架构师
【最佳实践】一文掌握并应用Elasticsearch中的GC实现垃圾日志处理
你是否了解 GC 日志?以及如何通过GC,来解决何时找到、何时处理以及如何处理垃圾日志?
2908 0
【最佳实践】一文掌握并应用Elasticsearch中的GC实现垃圾日志处理
|
CDN
点播试看功能最佳实践
## 简介 试看指用户在观看视频或者音频等内容时,只能观看指定时间(如前五分钟)的内容,通常用于会员等付费业务场景。 阿里云视频点播服务提供了试看的完整解决方案,您可自由设置试看时长(或观看完整视频),播放服务会根据设置提供含有试看限制的特定的播放地址,可借此来实现完整的试看功能。 ## 使用前提 试看的基本原理是,播放的CDN加速地址带有试看的指定时长信息,云端会对该信息进行鉴权,鉴
3764 0
|
小程序
微信小程序 - 自定义组件支持外部class或者style样式 (Component - externalClasses)
微信小程序 - 自定义组件支持外部class或者style样式 (Component - externalClasses)
1180 0
微信小程序 - 自定义组件支持外部class或者style样式 (Component - externalClasses)