Example usage for com.squareup.okhttp ResponseBody contentType

List of usage examples for com.squareup.okhttp ResponseBody contentType

Introduction

In this page you can find the example usage for com.squareup.okhttp ResponseBody contentType.

Prototype

public abstract MediaType contentType();

Source Link

Usage

From source file:org.hawkular.agent.monitor.dynamicprotocol.prometheus.HawkularPrometheusScraper.java

License:Apache License

@Override
protected OpenConnectionDetails openConnection(URL endpointUrl) throws IOException {
    Configuration.Builder bldr = new Configuration.Builder().useSsl(endpointUrl.getProtocol().equals("https"))
            .sslContext(sslContext).username(endpointConfig.getConnectionData().getUsername())
            .password(endpointConfig.getConnectionData().getPassword());

    BaseHttpClientGenerator httpClientGen = new BaseHttpClientGenerator(bldr.build());
    OkHttpClient httpClient = httpClientGen.getHttpClient();
    Request request = buildGetRequest(endpointUrl, httpClientGen);
    Call call = httpClient.newCall(request);
    Response response = call.execute();
    ResponseBody responseBody = response.body();
    InputStream inputStream = responseBody.byteStream();
    MediaType contentType = responseBody.contentType();

    return new OpenConnectionDetails(inputStream, (contentType != null) ? contentType.toString() : null);
}

From source file:qm.vp.kiev.qmhttplib.retrofit.Utils.java

License:Apache License

/**
 * Replace a {@link com.squareup.okhttp.Response} with an identical copy whose body is backed by a
 * {@link okio.Buffer} rather than a {@link okio.Source}.
 *//*from   www. ja va2s .  c o m*/
static Response readBodyToBytesIfNecessary(Response response) throws IOException {
    final ResponseBody body = response.body();
    if (body == null) {
        return response;
    }

    BufferedSource source = body.source();
    final Buffer buffer = new Buffer();
    buffer.writeAll(source);
    source.close();

    return response.newBuilder().body(new ResponseBody() {
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public BufferedSource source() {
            return buffer.clone();
        }
    }).build();
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override//w  w w.  j ava 2  s .c o m
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {
                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client)
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
                    return new Converter<ResponseBody, String>() {
                        @Override
                        public String convert(ResponseBody value) throws IOException {
                            try {
                                return value.string();
                            } catch (IOException e) {
                                // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                                throw new RuntimeException("wrapper", e);
                            }
                        }
                    };
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi"));

    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void rawResponseContentTypeAndLengthButNoSource() throws IOException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(new ToStringConverterFactory()).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi").addHeader("Content-Type", "text/greeting"));

    Response<String> response = example.getString().execute();
    assertThat(response.body()).isEqualTo("Hi");
    ResponseBody rawBody = response.raw().body();
    assertThat(rawBody.contentLength()).isEqualTo(2);
    assertThat(rawBody.contentType().toString()).isEqualTo("text/greeting");
    try {//from   w w  w. j  a va 2  s  . c  o  m
        rawBody.source();
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Cannot read raw response body of a converted body.");
    }
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void emptyResponse() throws IOException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(new ToStringConverterFactory()).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("").addHeader("Content-Type", "text/stringy"));

    Response<String> response = example.getString().execute();
    assertThat(response.body()).isEqualTo("");
    ResponseBody rawBody = response.raw().body();
    assertThat(rawBody.contentLength()).isEqualTo(0);
    assertThat(rawBody.contentType().toString()).isEqualTo("text/stringy");
}

From source file:retrofit.converter.GsonConverter.java

License:Apache License

@Override
public Object fromBody(ResponseBody body, Type type) throws IOException {
    Charset charset = this.charset;
    if (body.contentType() != null) {
        charset = body.contentType().charset(charset);
    }// ww  w.  ja  v  a 2 s  .  com

    InputStream is = body.byteStream();
    try {
        return gson.fromJson(new InputStreamReader(is, charset), type);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:retrofit.KGsonConverter.java

License:Apache License

public T fromBody(ResponseBody value, Request request) throws IOException {
    String string = value.string();
    Reader reader = new InputStreamReader((new ByteArrayInputStream(string.getBytes())), Util.UTF_8);
    try {//from   ww w. ja  v  a  2 s .  com
        T t = typeAdapter.fromJson(reader);
        if (t instanceof Result) {
            KResult kResult = (KResult) t;
            if (kResult != null && kResult.isSuccess()) {
                Entry entry = new Entry();

                entry.data = string.getBytes("UTF-8");
                entry.mimeType = value.contentType().toString();
                cache.put(request.urlString(), entry);
            }
        }
        return t;
    } finally {
        Utils.closeQuietly(reader);
    }
}

From source file:retrofit.KOkHttpCall.java

License:Apache License

private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse, com.squareup.okhttp.Request request)
        throws IOException {
    ResponseBody rawBody = rawResponse.body();

    // Remove the body's source (the only stateful object) so we can pass the response along.
    rawResponse = rawResponse.newBuilder()
            .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();

    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
        try {/*w  w w  .  j a  v a  2s.  c  o m*/
            // Buffer the entire body to avoid future I/O.
            ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody);
            return Response.error(bufferedBody, rawResponse);
        } finally {
            closeQuietly(rawBody);
        }
    }

    if (code == 204 || code == 205) {
        return Response.success(null, rawResponse);
    }

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {

        T body;
        if (responseConverter instanceof KGsonConverter) {
            KGsonConverter<T> converter = (KGsonConverter<T>) responseConverter;
            body = converter.fromBody(catchingBody, request);
        } else {
            body = responseConverter.fromBody(catchingBody);
        }
        return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
        // If the underlying source threw an exception, propagate that rather than indicating it was
        // a runtime exception.
        catchingBody.throwIfCaught();
        throw e;
    }
}

From source file:retrofit.OkHttpCall.java

License:Apache License

private Response<T> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body();

    // Remove the body's source (the only stateful object) so we can pass the response along.
    rawResponse = rawResponse.newBuilder()
            .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();

    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
        try {// w  w w.j av a2s .  c om
            // Buffer the entire body to avoid future I/O.
            ResponseBody bufferedBody = Utils.readBodyToBytesIfNecessary(rawBody);
            return Response.error(bufferedBody, rawResponse);
        } finally {
            closeQuietly(rawBody);
        }
    }

    if (code == 204 || code == 205) {
        return Response.success(null, rawResponse);
    }

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {
        T body = responseConverter.convert(catchingBody);
        return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
        // If the underlying source threw an exception, propagate that rather than indicating it was
        // a runtime exception.
        catchingBody.throwIfCaught();
        throw e;
    }
}

From source file:retrofit2.CallTest.java

License:Apache License

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override// w  w w . j a va  2s.co m
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {
                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client)
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                        Retrofit retrofit) {
                    return new Converter<ResponseBody, String>() {
                        @Override
                        public String convert(ResponseBody value) throws IOException {
                            try {
                                return value.string();
                            } catch (IOException e) {
                                // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                                throw new RuntimeException("wrapper", e);
                            }
                        }
                    };
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi"));

    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}