Example usage for com.squareup.okhttp ResponseBody create

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

Introduction

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

Prototype

public static ResponseBody create(final MediaType contentType, byte[] content) 

Source Link

Document

Returns a new response body that transmits content .

Usage

From source file:com.magnet.max.android.tests.MagnetGsonConverterTest.java

License:Apache License

@SmallTest
public void testPrimitiveTypeUnmarshalling() {
    Converter magnetGsonConverter = magnetGsonConverterFactory.get(Integer.class);
    try {/*  w w  w . java 2s. c om*/
        Integer intValue = (Integer) magnetGsonConverter
                .fromBody(ResponseBody.create(MediaType.parse("application/json"), "1"));
        assertEquals(1, intValue.intValue());
    } catch (IOException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.client.HttpCloudFoundryClientTest.java

License:Apache License

@Test
void createRetryInterceptorShouldNotRefreshTokenOnBadCredentials() {
    Request request = new Request.Builder().url("http://duke.of.url").build();
    ResponseBody body = ResponseBody.create(MediaType.parse("application/octet-stream"), "Bad credentials");
    Response response401 = new Response.Builder().code(401).request(request).body(body).protocol(HTTP_1_1)
            .build();/*from ww w  .j a  v a  2s .  co  m*/
    Interceptor.Chain chain = mock(Interceptor.Chain.class);

    when(chain.request()).thenReturn(request);
    try {
        when(chain.proceed(any())).thenReturn(response401);
    } catch (IOException e) {
        fail("Should not happen!");
    }

    HttpCloudFoundryClient cloudFoundryClient = new HttpCloudFoundryClient("account", "appsManUri",
            "metricsUri", "host", "user", "password");
    Response response = cloudFoundryClient.createRetryInterceptor(chain);

    try {
        verify(chain, times(1)).proceed(eq(request));
    } catch (IOException e) {
        fail("Should not happen!");
    }
    assertThat(response).isEqualTo(response401);
}

From source file:com.shopify.buy.data.MockResponder.java

License:Open Source License

@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();
    String key = currentTestName.get() + '_' + Integer.toString(currentTestRequestIndex.getAndIncrement());

    JsonElement element = data.get(key);
    JsonObject responseJson = element.getAsJsonObject();
    int code = responseJson.get(KEY_CODE).getAsInt();
    String message = responseJson.get(KEY_MESSAGE).getAsString();
    String body = responseJson.get(KEY_BODY).getAsString();

    if (code >= 400) {
        retrofit.client.Response retrofitResponse = new retrofit.client.Response(request.urlString(), code,
                "reason", Collections.EMPTY_LIST, new TypedString(body));
        throw RetrofitError.httpError(request.urlString(), retrofitResponse, null, null);
    }//from ww w .  ja  v  a2 s.c o m

    MediaType contentType = MediaType.parse("application/json; charset=utf-8");
    return new Response.Builder().protocol(Protocol.HTTP_1_1).code(code).request(request)
            .body(ResponseBody.create(contentType, body)).message(message).addHeader("key", "value").build();
}

From source file:com.shopify.buy.data.MockResponseGenerator.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    File file = new File(context.getExternalFilesDir(null), "MobileBuy.json");

    if (file == null) {
        return chain.proceed(chain.request());
    }//from ww w  .j a  va  2 s.co m

    if (!file.exists()) {
        file.createNewFile();
    }

    String jsonKey = currentTestName.get() + '_' + Integer.toString(currentTestRequestIndex.getAndIncrement());

    Request request = chain.request();
    Response response = chain.proceed(request);
    String bodyString = response.body().string();

    JsonObject jsonValue = new JsonObject();
    jsonValue.addProperty(MockResponder.KEY_BODY, bodyString);
    jsonValue.addProperty(MockResponder.KEY_CODE, response.code());
    jsonValue.addProperty(MockResponder.KEY_MESSAGE, response.message());

    FileOutputStream fOut = new FileOutputStream(file, true);
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(fOut));
    writer.println("\"" + jsonKey + "\":" + jsonValue.toString() + ",");

    if (!isPartialAddressTestAdded.getAndSet(true)) {
        writer.println(TEST_WITH_PARTIAL_ADDRESS_RESPONSE);
    }

    writer.flush();
    fOut.flush();
    writer.close();
    fOut.close();

    MediaType contentType = response.body().contentType();
    return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
}

From source file:com.vavian.mockretrofitrequests.rest.service.FakeInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Response response = null;//from  www . j av a  2s  .c  o  m
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "---- DEBUG --- DEBUG -- DEBUG - DEBUG -- DEBUG --- DEBUG ----");
        Log.d(TAG, "----                FAKE SERVER RESPONSES                ----");
        String responseString;
        // Get Request URI.
        final URI uri = chain.request().uri();
        Log.d(TAG, "---- Request URL: " + uri.toString());
        // Get Query String.
        final String query = uri.getQuery();
        // Parse the Query String.
        final String[] parsedQuery = query.split("=");
        if (parsedQuery[0].equalsIgnoreCase("id") && parsedQuery[1].equalsIgnoreCase("1")) {
            responseString = TEACHER_ID_1;
        } else if (parsedQuery[0].equalsIgnoreCase("id") && parsedQuery[1].equalsIgnoreCase("2")) {
            responseString = TEACHER_ID_2;
        } else {
            responseString = "";
        }

        response = new Response.Builder().code(200).message(responseString).request(chain.request())
                .protocol(Protocol.HTTP_1_0)
                .body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
                .addHeader("content-type", "application/json").build();

        Log.d(TAG, "---- DEBUG --- DEBUG -- DEBUG - DEBUG -- DEBUG --- DEBUG ----");
    } else {
        response = chain.proceed(chain.request());
    }

    return response;
}

From source file:com.yandex.disk.rest.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String hash = Integer.toHexString(chain.hashCode());
    String sendPrefix = hash + SEND_PREFIX;
    String receivePrefix = hash + RECEIVE_PREFIX;

    if (logWire) {
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            logger.info(sendPrefix + "request: " + requestBody);
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            byte[] requestBuffer = ByteStreams.toByteArray(buffer.inputStream());
            logBuffer(sendPrefix, requestBuffer);
        }/* w  ww .java 2s.  co m*/
        request = request.newBuilder().removeHeader("Accept-Encoding").addHeader("Accept-Encoding", "").build();
    }

    logger.info(sendPrefix + request.method() + " " + request.url());
    logger.info(sendPrefix + "on " + chain.connection());
    logHeaders(sendPrefix, request.headers());

    Response response = chain.proceed(request);
    logger.info(receivePrefix + response.protocol() + " " + response.code() + " " + response.message());
    logHeaders(receivePrefix, response.headers());

    if (logWire) {
        ResponseBody body = response.body();
        byte[] responseBuffer = ByteStreams.toByteArray(body.byteStream());
        response = response.newBuilder().body(ResponseBody.create(body.contentType(), responseBuffer)).build();
        logBuffer(receivePrefix, responseBuffer);
    }

    return response;
}

From source file:retrofit.KOkHttpCall.java

License:Apache License

private Response<T> execCacheRequest(Request request) {
    if (responseConverter instanceof KGsonConverter) {
        KGsonConverter<T> converter = (KGsonConverter<T>) responseConverter;
        Cache cache = converter.getCache();
        if (cache == null) {
            return null;
        }/*from   w w w . jav  a  2s  . c  o m*/
        Entry entry = cache.get(request.urlString());// ?entry
        if (entry != null && entry.data != null) {// ?
            MediaType contentType = MediaType.parse(entry.mimeType);
            byte[] bytes = entry.data;
            try {
                com.squareup.okhttp.Response rawResponse = new com.squareup.okhttp.Response.Builder()//
                        .code(200).request(request).protocol(Protocol.HTTP_1_1)
                        .body(ResponseBody.create(contentType, bytes)).build();
                return parseResponse(rawResponse, request);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:retrofit.ResponseTest.java

License:Apache License

@Test
public void error() {
    ResponseBody errorBody = ResponseBody.create(null, "Broken!");
    Response<?> response = Response.error(400, errorBody);
    assertThat(response.raw()).isNotNull();
    assertThat(response.code()).isEqualTo(400);
    assertThat(response.message()).isNull();
    assertThat(response.headers().size()).isZero();
    assertThat(response.isSuccess()).isFalse();
    assertThat(response.body()).isNull();
    assertThat(response.errorBody()).isSameAs(errorBody);
}

From source file:retrofit.ResponseTest.java

License:Apache License

@Test
public void errorWithSuccessCodeThrows() {
    ResponseBody errorBody = ResponseBody.create(null, "Broken!");
    try {//w w  w  . jav  a 2 s.  com
        Response.error(200, errorBody);
        fail();
    } catch (IllegalArgumentException e) {
        assertThat(e).hasMessage("code < 400: 200");
    }
}

From source file:retrofit.ResponseTest.java

License:Apache License

@Test
public void errorWithRawResponse() {
    ResponseBody errorBody = ResponseBody.create(null, "Broken!");
    Response<?> response = Response.error(errorBody, errorResponse);
    assertThat(response.raw()).isSameAs(errorResponse);
    assertThat(response.code()).isEqualTo(400);
    assertThat(response.message()).isEqualTo("Broken!");
    assertThat(response.headers().size()).isZero();
    assertThat(response.isSuccess()).isFalse();
    assertThat(response.body()).isNull();
    assertThat(response.errorBody()).isSameAs(errorBody);
}