URLConnectionHttpClientWrapper.java

  1. /*
  2.  * Copyright (C) 2021 B3Partners B.V.
  3.  *
  4.  * SPDX-License-Identifier: MIT
  5.  *
  6.  */

  7. package nl.b3p.brmo.util.http.wrapper;

  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.net.HttpURLConnection;
  11. import java.net.URI;
  12. import java.net.URLConnection;
  13. import nl.b3p.brmo.util.http.HttpClientWrapper;
  14. import nl.b3p.brmo.util.http.HttpResponseWrapper;

  15. /**
  16.  * Wraps a standard Java HttpURLConnection or HttpsURLConnection.
  17.  *
  18.  * @author Matthijs Laan
  19.  */
  20. public class URLConnectionHttpClientWrapper
  21.     implements HttpClientWrapper<HttpURLConnection, HttpURLConnection> {
  22.   @Override
  23.   public HttpResponseWrapper request(URI uri, String... requestHeaders) throws IOException {
  24.     URLConnection connection = uri.toURL().openConnection();
  25.     if (!(connection instanceof HttpURLConnection)) {
  26.       throw new IllegalArgumentException("Expected HttpURLConnection instance for URI " + uri);
  27.     }
  28.     HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
  29.     httpURLConnection.setInstanceFollowRedirects(true);
  30.     if (requestHeaders.length % 2 != 0) {
  31.       throw new IllegalArgumentException();
  32.     }
  33.     for (int i = 0; i < requestHeaders.length; i += 2) {
  34.       httpURLConnection.setRequestProperty(requestHeaders[i], requestHeaders[i + 1]);
  35.     }

  36.     beforeRequest(httpURLConnection);
  37.     httpURLConnection.connect();

  38.     return wrapResponse(httpURLConnection);
  39.   }

  40.   /**
  41.    * Called before doing a request, override to modify or log it.
  42.    *
  43.    * @param httpURLConnection The HttpURLConnection that will be used, can be modified
  44.    */
  45.   @Override
  46.   public void beforeRequest(HttpURLConnection httpURLConnection) {}

  47.   /**
  48.    * Wraps a HttpURLConnection after HttpURLConnection.connect() has been called, override to modify
  49.    * or log it.
  50.    *
  51.    * @param httpURLConnection The URL connection to be wrapped
  52.    * @return The wrapped response
  53.    */
  54.   @Override
  55.   public HttpResponseWrapper wrapResponse(HttpURLConnection httpURLConnection) {
  56.     return new HttpResponseWrapper() {
  57.       @Override
  58.       public int getStatusCode() throws IOException {
  59.         return httpURLConnection.getResponseCode();
  60.       }

  61.       @Override
  62.       public String getHeader(String header) {
  63.         return httpURLConnection.getHeaderField(header);
  64.       }

  65.       @Override
  66.       public InputStream getResponseBody() throws IOException {
  67.         return httpURLConnection.getInputStream();
  68.       }
  69.     };
  70.   }
  71. }