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

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

There is a newer version: 1.0.4
Show newest version
package com.despegar.http.client;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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

public abstract class HttpMethod {

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

    private String url;

    private String name;

    private Map> headers;

    private boolean doOutput;

    public HttpMethod(String url, String name, boolean doOutput) {
        this.url = url;
        this.name = name;
        this.headers = new HashMap>();
        this.doOutput = doOutput;
    }

    public void addHeader(String name, String value) {
        if (!this.headers.containsKey(name)) {
            List values = new ArrayList();
            values.add(value);
            this.headers.put(name, values);
        } else {
            this.headers.get(name).add(value);
        }
    }

    protected String getURL() {
        return this.url;
    }

    protected String getName() {
        return this.name;
    }

    protected Map> getHeaders() {
        return this.headers;
    }

    protected abstract void writeBody(HttpURLConnection connection) throws IOException;

    protected HttpResponse execute(HttpClient httpClient) throws HttpClientException {
        try {
            LOGGER.debug("Executing {} ...", this);
            HttpURLConnection connection = httpClient.openConnection(this.getURL());
            connection.setDoOutput(this.doOutput);
            connection.setRequestMethod(this.getName());
            for (Entry> headersEntry : this.getHeaders().entrySet()) {
                String headerName = headersEntry.getKey();
                for (String headerValue : headersEntry.getValue()) {
                    connection.addRequestProperty(headerName, headerValue);
                }
            }
            this.writeBody(connection);
            HttpResponse response = httpClient.execute(connection);
            LOGGER.debug("{} executed with response {}", this, response);
            return response;
        } catch (IOException e) {
            throw new HttpClientException(String.format("An error has occurred trying to execute %s", this), e);
        }
    }

    @Override
    public String toString() {
        return "HttpMethod [url=" + this.url + ", name=" + this.name + ", headers=" + this.headers + ", doOutput="
            + this.doOutput + "]";
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy