Posting with HttpClient

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

时间: 2024-08-26 11:03:01

Posting with HttpClient的相关文章

关于 C# HttpClient的 请求

Efficiently Streaming Large HTTP Responses With HttpClient Downloading large files with HttpClient and you see that it takes lots of memory space? This post is probably for you. Let's see how to efficiently streaming large HTTP responses with HttpCli

使用httpclient抓取时,netstat 发现很多time_wait连接

http://wiki.apache.org/HttpComponents/FrequentlyAskedConnectionManagementQuestions 1. Connections in TIME_WAIT State After running your HTTP application, you use the netstat command and detect a lot of connections in stateTIME_WAIT. Now you wonder wh

用gson和httpclient调用微信公众平台API

吐槽:微信api很无语,部分用xml,部分用json. 最近在找如何调用微信公众平台关于json相关的api比较方便,最后发现httpcliect和gson不错.如果你有更好的方式,请告诉我. 以下代码先了解如何使用gson和httpclient,有功夫再整到我的sophia里 import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.

HttpClient使用详解 (一)

Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性.因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入. 一.简介 HttpClient是Apache Jakarta Common下的子项目,用

SpringMVC template和HttpClient post提交

服务器的接口如果是springmvc客户端除了用springmvc提供的RestTemplate请求如下 public class RestClient { private static Logger logger = Logger.getLogger(RestClient.class); @SuppressWarnings({ rawtypes, unchecked }) public static Object post(String url, Map<string, object="

Httpclient处理摘要认证

虽然摘要认证的安全性比BASIC认证提高了不少,但是从接口调用上来看,并不比BASIC认证复杂,而且Realm和Scheme参数都可以为空,这时候就和BASIC认证的调用方式一模一样了. import java.net.URI; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.Credentia

【黑马Android】(06)使用HttpClient方式请求网络/网易新闻案例

使用HttpClient方式请求网络 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"

使用Apache HttpClient访问网络(实现手机端注册,服务器返回信息)

这两天看了点网络编程,根据教程写了一个小的注册服务,贴出来. 本实例分别演示用GET方式和POST方式想服务器发送注册信息,分为客户端和服务器端两部分: 客户端注册用户信息,发送到服务器 服务器端接收信息并向客户端返回注册信息.(服务器端使用J2EE中的Servlet技术来实现,并发布到Tomcat服务器上) 代码运行效果如下: 客户端: 1.点击get注册按钮后: 客户端: 服务器端: 2.点击post注册按钮后: 客户端: 服务器端: 3.当服务器端关闭时: 客户端注册信息时会提示链接超时:

HttpClient(四)-- 使用代理IP 和 超时设置

1.代理IP的用处: 在爬取网页的时候,有的目标站点有反爬虫机制,对于频繁访问站点以及规则性访问站点的行为,会采集屏蔽IP措施.这时候,就可以使用代理IP,屏蔽一个就换一个IP. 2.代理IP分类: 代理IP的话 也分几种: 透明代理.匿名代理.混淆代理.高匿代理,一般使用高匿代理. 3.使用 RequestConfig.custom().setProxy(proxy).build() 来设置代理IP: public static void main(String[] args) throws