Postagem com HttpClient

Postagem com HttpClient

1. Visão geral

Neste tutorial -we’ll POST with the HttpClient 4 - usando a primeira autorização e, em seguida, a API HttpClient fluente.

Finalmente, discutiremos como fazer upload de um arquivo usando Httpclient.

Leitura adicional:

Configuração avançada do HttpClient

Configurações HttpClient para casos de uso avançados.

Read more

Como enviar cookies personalizados com o Apache HttpClient 4.

Read more

HttpClient com SSL

Exemplo de como configurar o HttpClient com SSL.

Read more

2. POST básico

Primeiro, vamos examinar um exemplo simples e enviar uma solicitação POST usandoHttpClient.

Faremos um POST com dois parâmetros - “username” e “password“:

@Test
public void whenSendPostRequestUsingHttpClient_thenCorrect()
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://www.example.com");

    List params = new ArrayList();
    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();
}

Observe como usamosList deNameValuePair para incluir parâmetros na solicitação POST.

3. POST com autorização

A seguir, vamos ver como fazer um POST com credenciais de autenticação usandoHttpClient.

No exemplo a seguir, enviamos uma solicitação POST para um URL protegido com autenticação básica adicionando um cabeçalho de autorização:

@Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_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();
}

4. POST com JSON

Agora - vamos ver como enviar uma solicitação POST com um corpo JSON usandoHttpClient.

No exemplo a seguir - estamos enviando algumas informações deperson (id, name) como JSON:

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

Observe como estamos usandoStringEntity para definir o corpo da solicitação.

We’re also setting the ContentType header to application/json para fornecer ao servidor as informações necessárias sobre a representação do conteúdo que enviamos.

5. POST com oHttpClient Fluent API

A seguir, vamos fazer um POST com a API FluentHttpClient.

Vamos enviar uma solicitação com dois parâmetros “username” e “password“:

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

6. Solicitação POST multiparte

Agora, vamos POSTAR uma solicitação multiparte.

PublicaremosFile, nome de usuário e senha usandoMultipartEntityBuilder:

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

7. Faça upload de umFile usandoHttpClient

A seguir, vamos ver como fazer upload de umFile usando oHttpClient.

Faremos o upload do arquivo “test.txt” usandoMultipartEntityBuilder:

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

8. ObterFile Upload Progresso

Finalmente - vamos ver como obter o progresso do upload deFile usandoHttpClient.

No exemplo a seguir, estenderemosHttpEntityWrapper para obter visibilidade do processo de upload.

Primeiro - aqui está o método de upload:

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

Também adicionaremos a interfaceProgressListener que nos permite observar o andamento do upload:

public static interface ProgressListener {
    void progress(float percentage);
}

E aqui está nossa versão estendida deHttpEntityWrapperProgressEntityWrapper“:

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

E a versão estendida deFilterOutputStreamCountingOutputStream“:

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

Observe que:

  • Ao estenderFilterOutputStream para “CountingOutputStream” –, estamos substituindo o métodowrite() para contar os bytes gravados (transferidos)

  • Ao estenderHttpEntityWrapper para “ProgressEntityWrapper” –, estamos substituindo o métodowriteTo() para usar nosso“CountingOutputStream”

9. Conclusão

Neste tutorial, ilustramos as maneiras mais comuns de enviar Solicitações POST HTTP comApache HttpClient 4.

Aprendemos como enviar uma solicitação POST com autorização, como postar usando a API fluenteHttpClient e como fazer upload de um arquivo e monitorar seu progresso.

A implementação de todos esses exemplos e trechos de código pode ser encontrada emthe github project.