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

io.swagger.io.HttpClient Maven / Gradle / Ivy

There is a newer version: 1.0.73
Show newest version
package io.swagger.io;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HttpClient {
    private String baseUrl;
    private Map queryParams = new HashMap<>();
    private Map headers = new HashMap<>();
    private CloseableHttpClient httpClient;
    private CloseableHttpResponse response;


    public HttpClient(String url) {
        baseUrl = url;
    }

    public void addQueryParam(String name, String value) {
        queryParams.put(name, value);
    }

    public void addHeader(String name, String value) {
        headers.put(name, value);
    }

    public InputStream execute() throws URISyntaxException, IOException {
        httpClient = HttpClients.createDefault();

        URIBuilder uriBuilder = new URIBuilder(baseUrl);
        for (Map.Entry queryParam : queryParams.entrySet()) {
            uriBuilder.addParameter(queryParam.getKey(), queryParam.getValue());
        }

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        for (Map.Entry header : headers.entrySet()) {
            httpGet.addHeader(header.getKey(), header.getValue());
        }

        response = httpClient.execute(httpGet);
        return response.getEntity().getContent();
    }

    public void close() {
        try {
            response.close();
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
        }

        try {
            httpClient.close();
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy