/** Returns a new response body that transmits {@code content}. */ public static ResponseBody create(final @Nullable MediaType contentType, byte[] content) { Buffer buffer = new Buffer().write(content); return create(contentType, content.length, buffer); }
@Override public Response<?> call() { return Response.error(500, ResponseBody.create(null, new byte[0])); } };
static ResponseBody buffer(final ResponseBody body) throws IOException { Buffer buffer = new Buffer(); body.source().readAll(buffer); return ResponseBody.create(body.contentType(), body.contentLength(), buffer); }
/** Returns a new response body that transmits {@code content}. */ public static ResponseBody create(@Nullable MediaType contentType, ByteString content) { Buffer buffer = new Buffer().write(content); return create(contentType, content.size(), buffer); }
/** * Returns a new response body that transmits {@code content}. If {@code contentType} is non-null * and lacks a charset, this will use UTF-8. */ public static ResponseBody create(@Nullable MediaType contentType, String content) { Charset charset = UTF_8; if (contentType != null) { charset = contentType.charset(); if (charset == null) { charset = UTF_8; contentType = MediaType.parse(contentType + "; charset=utf-8"); } } Buffer buffer = new Buffer().writeString(content, charset); return create(contentType, buffer.size(), buffer); }
/** Returns a new response body that transmits {@code content}. */ public static ResponseBody create(final @Nullable MediaType contentType, byte[] content) { Buffer buffer = new Buffer().write(content); return create(contentType, content.length, buffer); }
private Response<T> tooManyRequestsError() { return Response.error(ERROR_CODE, ResponseBody.create(MediaType.parse("text/plain"), ERROR_MESSAGE)); } };
static ResponseBody buffer(final ResponseBody body) throws IOException { Buffer buffer = new Buffer(); body.source().readAll(buffer); return ResponseBody.create(body.contentType(), body.contentLength(), buffer); }
/** Returns a new response body that transmits {@code content}. */ public static ResponseBody create(@Nullable MediaType contentType, ByteString content) { Buffer buffer = new Buffer().write(content); return create(contentType, content.size(), buffer); }
/** * Peeks up to {@code byteCount} bytes from the response body and returns them as a new response * body. If fewer than {@code byteCount} bytes are in the response body, the full response body is * returned. If more than {@code byteCount} bytes are in the response body, the returned value * will be truncated to {@code byteCount} bytes. * * <p>It is an error to call this method after the body has been consumed. * * <p><strong>Warning:</strong> this method loads the requested bytes into memory. Most * applications should set a modest limit on {@code byteCount}, such as 1 MiB. */ public ResponseBody peekBody(long byteCount) throws IOException { BufferedSource peeked = body.source().peek(); Buffer buffer = new Buffer(); peeked.request(byteCount); buffer.write(peeked, Math.min(byteCount, peeked.getBuffer().size())); return ResponseBody.create(body.contentType(), buffer.size(), buffer); }
/** like {@link #get(Request)} except doesn't throw unsupported on not found */ Response call(Request request) throws IOException { try (Response response = client.newCall(request).execute()) { if (!HttpHeaders.hasBody(response)) return response; // buffer response so tests can read it. Otherwise the finally block will drop it ResponseBody toReturn; try (ResponseBody body = response.body()) { Buffer buffer = new Buffer(); body.source().readAll(buffer); toReturn = ResponseBody.create(body.contentType(), body.contentLength(), buffer); } return response.newBuilder().body(toReturn).build(); } }
@Test public void testRegisterFailed() throws IOException { when(call.execute()).thenReturn(responseBuilder .body(ResponseBody.create(MediaType.parse("text/html"), "<body>Message<br/></body>")) .message("") .code(HttpURLConnection.HTTP_OK) .build()); UserServices.Callback callback = mock(UserServices.Callback.class); userServices.login("username", "password", true, callback); verify(callback).onError(throwableCaptor.capture()); //noinspection ThrowableResultOfMethodCallIgnored assertThat(throwableCaptor.getValue().getMessage()).contains("Message"); }
@Test public void noCacheAndKnownContentLengthDispatchToStats() throws Exception { responses.add(responseOf(ResponseBody.create(null, new byte[10]))); Action action = TestUtils.mockAction(URI_KEY_1, URI_1); final CountDownLatch latch = new CountDownLatch(1); networkHandler.load(picasso, action.request, new RequestHandler.Callback() { @Override public void onSuccess(Result result) { verify(stats).dispatchDownloadFinished(10); latch.countDown(); } @Override public void onError(@NonNull Throwable t) { throw new AssertionError(t); } }); assertThat(latch.await(10, SECONDS)).isTrue(); }
@Test public void testSubmitParsingNoFnidValue() throws IOException { when(call.execute()).thenReturn(createResponseBuilder() .body(ResponseBody.create(MediaType.parse("text/html"), "<input \"name\"=\"fnid\">")) .message("") .code(HttpURLConnection.HTTP_OK) .build()); UserServices.Callback callback = mock(UserServices.Callback.class); userServices.submit(RuntimeEnvironment.application, "title", "url", true, callback); verify(callback).onError(any(Throwable.class)); }
@Test public void testSubmitParsingNoInput() throws IOException { when(call.execute()).thenReturn(createResponseBuilder() .body(ResponseBody.create(MediaType.parse("text/html"), "")) .message("") .code(HttpURLConnection.HTTP_OK) .build()); UserServices.Callback callback = mock(UserServices.Callback.class); userServices.submit(RuntimeEnvironment.application, "title", "url", true, callback); verify(callback).onError(any(Throwable.class)); }
@Test public void testSubmitParsingNoFnid() throws IOException { when(call.execute()).thenReturn(createResponseBuilder() .body(ResponseBody.create(MediaType.parse("text/html"), "<input \"name\"=\"hiddenfield\" value=\"unique\">")) .message("") .code(HttpURLConnection.HTTP_OK) .build()); UserServices.Callback callback = mock(UserServices.Callback.class); userServices.submit(RuntimeEnvironment.application, "title", "url", true, callback); verify(callback).onError(any(Throwable.class)); }
private Response mockHttpResponse() { return new okhttp3.Response.Builder() .request(new Request.Builder() .url("https://localhost/") .build()) .protocol(Protocol.HTTP_2) .code(200) .message("Intercepted") .body(ResponseBody.create(MediaType.parse("text/plain; charset=utf-8"), "fakeResponse")) .build(); }
@Test public void cachedResponseDoesNotDispatchToStats() throws Exception { responses.add(responseOf(ResponseBody.create(null, new byte[10])) .newBuilder() .cacheResponse(responseOf(null)) .build()); Action action = TestUtils.mockAction(URI_KEY_1, URI_1); final CountDownLatch latch = new CountDownLatch(1); networkHandler.load(picasso, action.request, new RequestHandler.Callback() { @Override public void onSuccess(Result result) { verifyZeroInteractions(stats); latch.countDown(); } @Override public void onError(@NonNull Throwable t) { throw new AssertionError(t); } }); assertThat(latch.await(10, SECONDS)).isTrue(); }
@Test public void doesNotForceLocalCacheOnlyWithAirplaneModeOffAndRetryCount() throws Exception { responses.add(responseOf(ResponseBody.create(null, new byte[10]))); Action action = TestUtils.mockAction(URI_KEY_1, URI_1); final CountDownLatch latch = new CountDownLatch(1); networkHandler.load(picasso, action.request, new RequestHandler.Callback() { @Override public void onSuccess(Result result) { try { assertThat(requests.takeFirst().cacheControl().toString()).isEmpty(); latch.countDown(); } catch (InterruptedException e) { throw new AssertionError(e); } } @Override public void onError(@NonNull Throwable t) { throw new AssertionError(t); } }); assertThat(latch.await(10, SECONDS)).isTrue(); }
@Test public void withZeroRetryCountForcesLocalCacheOnly() throws Exception { responses.add(responseOf(ResponseBody.create(null, new byte[10]))); Action action = TestUtils.mockAction(URI_KEY_1, URI_1); PlatformLruCache cache = new PlatformLruCache(0); BitmapHunter hunter = new BitmapHunter(picasso, dispatcher, cache, stats, action, networkHandler); hunter.retryCount = 0; hunter.hunt(); assertThat(requests.takeFirst().cacheControl().toString()).isEqualTo(CacheControl.FORCE_CACHE.toString()); }