seatgeek / spreedly-java

Java SDK for use with the Spreedly PCI-compliant vaulting service.
MIT License
0 stars 2 forks source link

Create default OkHttp3 client #2

Open dallasgutauckis opened 8 years ago

dallasgutauckis commented 8 years ago

Implementation:

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cc.protea.util.http.HttpClient;
import cc.protea.util.http.Request;
import cc.protea.util.http.Response;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;

public class OkHttp3SpreedlyClient implements HttpClient {
    @Override
    public Response execute(Request spreedlyRequest) throws IOException {
        final OkHttpClient client = new OkHttpClient();
        final Builder builder = new Builder().url(spreedlyRequest.getUrl());
        final Map<String, List<String>> headers = spreedlyRequest.getHeaders();
        final RequestBody requestBody = RequestBody.create(MediaType.parse(spreedlyRequest.getContentType()), spreedlyRequest.getBody());

        if (!headers.isEmpty()) {
            for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                List<String> values = entry.getValue();

                for (String value : values) {
                    builder.addHeader(entry.getKey(), value);
                }
            }
        }

        builder.method(spreedlyRequest.getMethod(), requestBody);

        final okhttp3.Request request = builder.build();

        okhttp3.Response response = client.newCall(request).execute();

        return fromOkResponse(response);
    }

    private Response fromOkResponse(okhttp3.Response response) {
        final Response outResponse = new Response();
        final Headers okHeaders = response.headers();
        final Set<String> names = okHeaders.names();
        final HashMap<String, List<String>> headers = new HashMap<String, List<String>>(names.size());

        outResponse.setResponseCode(response.code());
        outResponse.setResponseMessage(response.message());

        for (String name : names) {
            headers.put(name, okHeaders.values(name));
        }

        outResponse.setHeaders(headers);

        try {
            outResponse.setBody(response.body().string());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return outResponse;
    }
}
sddamico commented 8 years ago

lgtm