@Override public BufferedSource source() { return Okio.buffer(new ForwardingSource(delegate.source()) { @Override public long read(Buffer sink, long byteCount) throws IOException { try { return super.read(sink, byteCount); } catch (IOException e) { thrownException = e; throw e; } } }); }
@Override public BufferedSource source() { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; }
@Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody body = response.body()) { // Consume and discard the response body. body.source().readByteString(); } } });
@Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody body = response.body()) { // Consume and discard the response body. body.source().readByteString(); } } });
public void run() throws Exception { Request request = new Request.Builder() .url("https://api.github.com/gists/c2a7c39532239ff261be") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Gist gist = gistJsonAdapter.fromJson(response.body().source()); for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue().content); } } }
public final InputStream byteStream() { return source().inputStream(); }
@Override public void close() { Util.closeQuietly(source()); }
public void run() throws Exception { Request request = new Request.Builder() .url("https://publicobject.com/helloworld.txt") .build(); System.out.println("REQUEST 1 (new connection)"); try (Response response = client.newCall(request).execute()) { // Consume and discard the response body. response.body().source().readByteString(); } System.out.println("REQUEST 2 (pooled connection)"); try (Response response = client.newCall(request).execute()) { // Consume and discard the response body. response.body().source().readByteString(); } }
public static void main(String... args) throws Exception { OkHttpClient client = new OkHttpClient(); // Create request for remote resource. Request request = new Request.Builder() .url(ENDPOINT) .build(); // Execute the request and retrieve the response. try (Response response = client.newCall(request).execute()) { // Deserialize HTTP response to concrete type. ResponseBody body = response.body(); List<Contributor> contributors = CONTRIBUTORS_JSON_ADAPTER.fromJson(body.source()); // Sort list by the most contributions. Collections.sort(contributors, (c1, c2) -> c2.contributions - c1.contributions); // Output list of contributors. for (Contributor contributor : contributors) { System.out.println(contributor.login + ": " + contributor.contributions); } } }
/** See https://api.slack.com/methods/rtm.start. */ public RtmStartResponse rtmStart(String accessToken) throws IOException { HttpUrl url = baseUrl.newBuilder("rtm.start") .addQueryParameter("token", accessToken) .build(); Request request = new Request.Builder() .url(url) .build(); Call call = httpClient.newCall(request); try (Response response = call.execute()) { JsonAdapter<RtmStartResponse> jsonAdapter = moshi.adapter(RtmStartResponse.class); return jsonAdapter.fromJson(response.body().source()); } }
@Override public T convert(ResponseBody value) throws IOException { try { return adapter.decode(value.source()); } finally { value.close(); } } }
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 the response as a character stream. * * <p>If the response starts with a <a href="https://en.wikipedia.org/wiki/Byte_order_mark">Byte * Order Mark (BOM)</a>, it is consumed and used to determine the charset of the response bytes. * * <p>Otherwise if the response has a Content-Type header that specifies a charset, that is used * to determine the charset of the response bytes. * * <p>Otherwise the response bytes are decoded as UTF-8. */ public final Reader charStream() { Reader r = reader; return r != null ? r : (reader = new BomAwareReader(source(), charset())); }
/** * Returns the response as a byte array. * * <p>This method loads entire response body into memory. If the response body is very large this * may trigger an {@link OutOfMemoryError}. Prefer to stream the response body if this is a * possibility for your response. */ public final byte[] bytes() throws IOException { long contentLength = contentLength(); if (contentLength > Integer.MAX_VALUE) { throw new IOException("Cannot buffer entire body for content length: " + contentLength); } byte[] bytes; try (BufferedSource source = source()) { bytes = source.readByteArray(); } if (contentLength != -1 && contentLength != bytes.length) { throw new IOException("Content-Length (" + contentLength + ") and stream length (" + bytes.length + ") disagree"); } return bytes; }
/** See https://api.slack.com/methods/oauth.access. */ public OAuthSession exchangeCode(String code, HttpUrl redirectUrl) throws IOException { HttpUrl url = baseUrl.newBuilder("oauth.access") .addQueryParameter("client_id", clientId) .addQueryParameter("client_secret", clientSecret) .addQueryParameter("code", code) .addQueryParameter("redirect_uri", redirectUrl.toString()) .build(); Request request = new Request.Builder() .url(url) .build(); Call call = httpClient.newCall(request); try (Response response = call.execute()) { JsonAdapter<OAuthSession> jsonAdapter = moshi.adapter(OAuthSession.class); return jsonAdapter.fromJson(response.body().source()); } }
/** * Returns the response as a string. * * <p>If the response starts with a <a href="https://en.wikipedia.org/wiki/Byte_order_mark">Byte * Order Mark (BOM)</a>, it is consumed and used to determine the charset of the response bytes. * * <p>Otherwise if the response has a Content-Type header that specifies a charset, that is used * to determine the charset of the response bytes. * * <p>Otherwise the response bytes are decoded as UTF-8. * * <p>This method loads entire response body into memory. If the response body is very large this * may trigger an {@link OutOfMemoryError}. Prefer to stream the response body if this is a * possibility for your response. */ public final String string() throws IOException { try (BufferedSource source = source()) { Charset charset = Util.bomAwareCharset(source, charset()); return source.readString(charset); } }
/** * 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); }
private List<InetAddress> readResponse(String hostname, Response response) throws Exception { if (response.cacheResponse() == null && response.protocol() != Protocol.HTTP_2) { Platform.get().log(Platform.WARN, "Incorrect protocol: " + response.protocol(), null); } try { if (!response.isSuccessful()) { throw new IOException("response: " + response.code() + " " + response.message()); } ResponseBody body = response.body(); if (body.contentLength() > MAX_RESPONSE_SIZE) { throw new IOException("response size exceeds limit (" + MAX_RESPONSE_SIZE + " bytes): " + body.contentLength() + " bytes"); } ByteString responseBytes = body.source().readByteString(); return DnsRecordCodec.decodeAnswers(hostname, responseBytes); } finally { response.close(); } }
public void processResponse(Response response) { try { if (!response.isSuccessful()) { listener.onFailure(this, null, response); return; } ResponseBody body = response.body(); //noinspection ConstantConditions main body is never null MediaType contentType = body.contentType(); if (!isEventStream(contentType)) { listener.onFailure(this, new IllegalStateException("Invalid content-type: " + contentType), response); return; } // Replace the body with an empty one so the callbacks can't see real data. response = response.newBuilder().body(Util.EMPTY_RESPONSE).build(); ServerSentEventReader reader = new ServerSentEventReader(body.source(), this); try { listener.onOpen(this, response); while (reader.processNextEvent()) { } } catch (Exception e) { listener.onFailure(this, e, response); return; } listener.onClosed(this); } finally { response.close(); } }
@Override public T convert(ResponseBody value) throws IOException { BufferedSource source = value.source(); try { // Moshi has no document-level API so the responsibility of BOM skipping falls to whatever // is delegating to it. Since it's a UTF-8-only library as well we only honor the UTF-8 BOM. if (source.rangeEquals(0, UTF8_BOM)) { source.skip(UTF8_BOM.size()); } JsonReader reader = JsonReader.of(source); T result = adapter.fromJson(reader); if (reader.peek() != JsonReader.Token.END_DOCUMENT) { throw new JsonDataException("JSON document was not fully consumed."); } return result; } finally { value.close(); } } }