1. Información general
En este tutorial , publicaremos con HttpClient 4 , utilizando la primera autorización y luego la API fluida de HttpClient.
Finalmente, discutiremos cómo cargar un archivo usando Httpclient.
2. POST Básico
Primero, repasemos un ejemplo simple y enviemos una solicitud POST usando HttpClient .
Haremos una POST con dos parámetros: " nombre de usuario " y " contraseña ":
@Test public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("//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 cómo usamos una Lista de NameValuePair para incluir parámetros en la solicitud POST.
3. PUBLICAR con autorización
A continuación, veamos cómo hacer una POST con credenciales de autenticación utilizando HttpClient .
En el siguiente ejemplo, enviamos una solicitud POST a una URL protegida con autenticación básica agregando un encabezado de autorización:
@Test public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("//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. PUBLICAR con JSON
Ahora, veamos cómo enviar una solicitud POST con un cuerpo JSON usando HttpClient .
En el siguiente ejemplo, estamos enviando información de alguna persona ( id, nombre ) como JSON:
@Test public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("//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 cómo estamos usando StringEntity para establecer el cuerpo de la solicitud.
También estamos configurando el encabezado ContentType en application / json para brindarle al servidor la información necesaria sobre la representación del contenido que estamos enviando.
5. PUBLICAR con la API de HttpClient Fluent
A continuación, publiquemos con la API de HttpClient Fluent.
Vamos a enviar una solicitud con dos parámetros " nombre de usuario " y " contraseña ":
@Test public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException { HttpResponse response = Request.Post("//www.example.com").bodyForm( Form.form().add("username", "John").add("password", "pass").build()) .execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); }
6. Solicitud POST de varias partes
Ahora, PUBLICEMOS una Solicitud Multiparte.
Publicaremos un archivo , nombre de usuario y contraseña usando MultipartEntityBuilder :
@Test public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("//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. Cargue un archivo usando HttpClient
A continuación, veamos cómo cargar un archivo usando HttpClient.
Subiremos el archivo " test.txt " usando MultipartEntityBuilder :
@Test public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("//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. Obtener el progreso de carga de archivos
Finalmente, veamos cómo obtener el progreso de la carga de archivos usando HttpClient .
En el siguiente ejemplo, ampliaremos HttpEntityWrapper para obtener visibilidad del proceso de carga.
Primero, aquí está el método de carga:
@Test public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("//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(); }
También agregaremos la interfaz ProgressListener que nos permite observar el progreso de la carga:
public static interface ProgressListener { void progress(float percentage); }
Y aquí está nuestra versión extendida de 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())); } }
Y la versión extendida de FilterOutputStream " 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; } }
Tenga en cuenta que:
- When extending FilterOutputStream to “CountingOutputStream” – we are overriding the write() method to count the written (transferred) bytes
- When extending HttpEntityWrapper to “ProgressEntityWrapper” – we are overriding the writeTo() method to use our “CountingOutputStream”
9. Conclusion
In this tutorial, we illustrated the most common ways to send POST HTTP Requests with the Apache HttpClient 4.
We learned how to send a POST request with Authorization, how to post using HttpClient fluent API and how to upload a file and track its progress.
La implementación de todos estos ejemplos y fragmentos de código se puede encontrar en el proyecto github.