All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.despegar.http.client.HttpClient Maven / Gradle / Ivy

The newest version!
package com.despegar.http.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);

    static {
        try {
            /*
             * Modification based on
             * http://stackoverflow.com/questions/22355235/patch-request-using-jersey-client/39641592#39641592 in order
             * to allow PATCH method
             */
            Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
            methodsField.setAccessible(true);
            // get the methods field modifiers
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            // bypass the "private" modifier
            modifiersField.setAccessible(true);
            // remove the "final" modifier
            modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);
            /* valid HTTP methods */
            String[] methods = {"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"};
            // set the new methods - including patch
            methodsField.set(null, methods);
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
            /*
             * These exceptions should not happen
             */
            e.printStackTrace();
        }
    }

    public HttpClient(int maxConnectionsPerDestination) {
        LOGGER.debug("HttpClient created with {} max connections per destination", maxConnectionsPerDestination);
        System.setProperty("http.keepAlive", "true");
        System.setProperty("http.maxConnections", String.valueOf(maxConnectionsPerDestination));
    }

    protected HttpURLConnection openConnection(String spec) throws IOException {
        URL url = new URL(spec);
        return (HttpURLConnection) url.openConnection();
    }

    private byte[] readResponse(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        if (inputStream != null) {
        	byte[] buffer = new byte[10240];
            int read = inputStream.read(buffer);
            while (read > -1) {
                byteArrayOutputStream.write(buffer, 0, read);
                read = inputStream.read(buffer);
            }
            inputStream.close();
        }
        byteArrayOutputStream.flush();
        byteArrayOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    protected HttpResponse execute(HttpURLConnection connection) throws HttpClientException {
        try {
            int responseCode = connection.getResponseCode();
            byte[] body = null;
            if (responseCode >= 400) {
                body = this.readResponse(connection.getErrorStream());
            } else {
                body = this.readResponse(connection.getInputStream());
            }
            return new HttpResponse(responseCode, connection.getResponseMessage(), connection.getHeaderFields(), body);
        } catch (IOException e) {
            throw new HttpClientException("An error has occurred trying to connect to the server", e);
        }
    }

    public HttpResponse execute(HttpMethod httpMethod) throws HttpClientException {
        return httpMethod.execute(this);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy