HttpClient series -Post basics (c)

Brief

Learn how to use a simple POST, how to upload files, and so the scene

Basis POST

First, let's look at a simple example, and send a POST request to use HttpClient.

We will use two arguments - "username" and "password" carried POST:

@Test
public void test() 
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", "John"));
    params.add(new BasicNameValuePair("password", "pass"));
    httpPost.setEntity(new UrlEncodedFormEntity(params));
 
    HttpPost httpPost = new HttpPost("http://localhost:8080");

    CloseableHttpResponse response = client.execute(httpPost);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
复制代码

Notice how we use the List parameter contained in the POST request.

Authorized use POST

Next, let's look at how to use HttpClient to authenticate credentials POST.

In the following example - by adding the Authorization to use our basic identity verification URL sent in the Header claimed POST:

@Test
public void test()
  throws ClientProtocolException, IOException, AuthenticationException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080");


   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();
}
复制代码

Use JSON POST

Now - let's see how to send POST request to the JSON body use HttpClient.

We will Some Person (id, name) is sent as JSON - In the following example:

@Test
public void test() 
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080");

    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();
}
复制代码

Notice how we use the StringEntitybody to set the request.

We will also ContentType header is set application / jsonto provide the necessary information about the content we send representation to the server.

Carried out using HttpClient Form POST

Next, let's use HttpClient Fluent API conduct POST.

We will send a request with the two parameters "username" and "password" are:

@Test
public void test() 
  throws ClientProtocolException, IOException {
    HttpResponse response = Request.Post("http://localhost:8080").bodyForm(
      Form.form().add("username", "John").add("password", "pass").build())
      .execute().returnResponse();
 
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
复制代码

POST multi-parameter request

Now, let us send a multi-parameter request.

We will use the MultipartEntityBuilderreleased documents, useranme and password:

@Test
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() 
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080");

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

复制代码

Use HttpClient upload files

Next, let's look at how to use HttpClient to upload files.

We will use MultipartEntityBuilder upload "test.txt" file:

@Test
public void test() throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080");

    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();
}
复制代码

Get file upload progress

Finally - let's see how to use HttpClient to obtain file upload progress.

In the following example, we will extend HttpEntityWrapper to obtain visibility of the upload process.

First - this is the upload method:

@Test
public void test()
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:8080");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addBinaryBody("file", new File("test.txt"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
    HttpEntity multipart = builder.build();
 
    ProgressEntityWrapper.ProgressListener pListener = 
      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();
}
复制代码

We will also add an interface ProgressListener, allowing us to observe the progress of the upload:

public static interface ProgressListener {
    void progress(float percentage);
}
复制代码

This is our extended version of 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()));
    }
}
复制代码

The FilterOutputStream extended version 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;
    }
}
复制代码

note:

  • FilterOutputStream is extended CountingOutputStreamwhen - we rewrite the write () method to calculate the write (transfer) the number of bytes
  • The HttpEntityWrapper extended ProgressEntityWrappertime - we rewrite writeTo () method to use ourCountingOutputStream

summary

HttpClient to the basics of this article has introduced the end, I hope for your harvest.

Guess you like

Origin juejin.im/post/5d109bf1e51d45595319e35f