001package io.freefair.spring.okhttp.client;
002
003import kotlin.Pair;
004import okhttp3.Headers;
005import okhttp3.Response;
006import okhttp3.ResponseBody;
007import org.springframework.http.HttpHeaders;
008import org.springframework.http.HttpStatusCode;
009import org.springframework.http.client.ClientHttpResponse;
010import java.io.InputStream;
011
012/**
013 * OkHttp based {@link ClientHttpResponse} implementation.
014 *
015 * @author Lars Grefer
016 * @see OkHttpClientRequest
017 */
018public class OkHttpClientResponse implements ClientHttpResponse {
019    private final Response okHttpResponse;
020    private HttpHeaders springHeaders;
021
022    @Override
023    public HttpStatusCode getStatusCode() {
024        return HttpStatusCode.valueOf(okHttpResponse.code());
025    }
026
027    @Override
028    public String getStatusText() {
029        return okHttpResponse.message();
030    }
031
032    @Override
033    public void close() {
034        ResponseBody body = okHttpResponse.body();
035        if (body != null) {
036            body.close();
037        }
038    }
039
040    @Override
041    public InputStream getBody() {
042        ResponseBody body = okHttpResponse.body();
043        if (body != null) {
044            return body.byteStream();
045        } else {
046            return InputStream.nullInputStream();
047        }
048    }
049
050    @Override
051    public HttpHeaders getHeaders() {
052        if (springHeaders == null) {
053            springHeaders = convertHeaders(okHttpResponse.headers());
054        }
055        return springHeaders;
056    }
057
058    /**
059     * Converts the given {@link Headers OkHttp Headers} to {@link HttpHeaders Spring Web HttpHeaders}
060     */
061    static HttpHeaders convertHeaders(Headers okHttpHeaders) {
062        HttpHeaders springHeaders = new HttpHeaders();
063        for (Pair<? extends String, ? extends String> header : okHttpHeaders) {
064            springHeaders.add(header.getFirst(), header.getSecond());
065        }
066        return springHeaders;
067    }
068
069    public OkHttpClientResponse(final Response okHttpResponse) {
070        this.okHttpResponse = okHttpResponse;
071    }
072}