bit.changepurse.wdk.http.HTTPClient.java Source code

Java tutorial

Introduction

Here is the source code for bit.changepurse.wdk.http.HTTPClient.java

Source

/*
 * This file is part of ChangePurse.
 *
 * Copyright (c) 2014 Germn Fuentes Capella
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package bit.changepurse.wdk.http;

import static bit.changepurse.wdk.util.CheckedExceptionMethods.execute;

import java.io.Closeable;
import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * Documentation for Apache Http Client:
 * http://hc.apache.org/httpcomponents-client-ga/examples.html
 */
public class HTTPClient implements Closeable {

    private final CloseableHttpClient client;
    private final ActionRegistry registry;

    public HTTPClient(ActionRegistry aRegistry) {
        client = HttpClients.createDefault();
        registry = aRegistry;
    }

    public HTTPClient() {
        this(new ActionRegistry());
    }

    @Override
    public void close() throws IOException {
        if (client != null) {
            client.close();
        }
    }

    public HTTPResponse send(HTTPRequest request) {
        HTTPResponse response = process(request);
        HTTPStatusCode statusCode = response.getStatusCode();
        ActionHandler handler = registry.getHandler(statusCode);
        return handler.apply(this, request, response);
    }

    private HTTPResponse process(HTTPRequest request) {
        HttpRequestBase apacheRequest = request.build();
        try (CloseableHttpResponse apacheResponse = process(apacheRequest)) {
            return new HTTPResponse(apacheResponse);
        } catch (IOException e) {
            throw new HTTPException(e);
        }
    }

    protected CloseableHttpResponse process(HttpRequestBase apacheRequest) {
        return execute(client, apacheRequest);
    }
}