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

cloud.genesys.webmessaging.sdk.connector.okhttp.OkHttpResponse Maven / Gradle / Ivy

package cloud.genesys.webmessaging.sdk.connector.okhttp;

import cloud.genesys.webmessaging.sdk.connector.ApiClientConnectorResponse;
import okhttp3.Headers;
import okhttp3.Response;
import okhttp3.ResponseBody;

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

public class OkHttpResponse implements ApiClientConnectorResponse {
    private final Response response;
    private String responseBody;
    private boolean hasReadBody = false;

    public OkHttpResponse(Response response) {
        this.response = response;
    }

    @Override
    public int getStatusCode() {
        return response.code();
    }

    @Override
    public String getStatusReasonPhrase() {
        return response.message();
    }

    @Override
    public Map getHeaders() {
        Map map = new HashMap<>();
        Headers headers = response.headers();
        if (headers != null) {
            for (String name : headers.names()) {
                map.put(name, headers.get(name));
            }
        }
        return map;
    }

    @Override
    public boolean hasBody() {
        try {
            String bodyString = this.readBody();
            return (bodyString != null && !bodyString.isEmpty());
        }
        catch (IOException e) {
            return false;
        }
    }

    @Override
    public String readBody() throws IOException {
        if (hasReadBody)
            return responseBody;

        hasReadBody = true;
        ResponseBody body = response.body();
        responseBody = (body != null) ? body.string() : null;
        return responseBody;
    }

    @Override
    public InputStream getBody() throws IOException {
        ResponseBody body = response.body();
        return (body != null) ? body.byteStream() : null;
    }

    @Override
    public void close() throws Exception { }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy