Refine search
/** * 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 InputStream buildInputStream(ResponseBody responseBody) throws IOException { InputStream inputStream = responseBody.byteStream(); if (includeRawResponse) { // we have to buffer the entire input payload, so that after processing // it can be re-read and used to populate the rawResponse field. BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body Buffer buffer = source.buffer(); long size = buffer.size(); if (size > Integer.MAX_VALUE) { throw new UnsupportedOperationException( "Non-integer input buffer size specified: " + size); } int bufferSize = (int) size; BufferedInputStream bufferedinputStream = new BufferedInputStream(inputStream, bufferSize); bufferedinputStream.mark(inputStream.available()); return bufferedinputStream; } else { return inputStream; } }
static EncryptionResult load(File f) throws Exception { BufferedSource source=Okio.buffer(Okio.source(f)); byte[] iv=source.readByteArray(BLOCK_SIZE); byte[] encrypted=source.readByteArray(); source.close(); return new EncryptionResult(iv, encrypted); }
/** * Consumes the field name of the specified length and the optional colon and its optional * trailing space. Returns the number of bytes skipped. */ private long skipNameAndDivider(long length) throws IOException { source.skip(length); if (source.getBuffer().getByte(0) == ':') { source.skip(1L); length++; if (source.getBuffer().getByte(0) == ' ') { source.skip(1); length++; } } return length; } }
@Override public long read(Buffer sink, long byteCount) throws IOException { while (left == 0) { source.skip(padding); padding = 0; if ((flags & FLAG_END_HEADERS) != 0) return -1; readContinuationHeader(); // TODO: test case for empty continuation header? } long read = source.read(sink, Math.min(byteCount, left)); if (read == -1) return -1; left -= read; return read; }
if (!source.request(1)) { throw syntaxError("Unterminated escape sequence"); byte escaped = buffer.readByte(); switch (escaped) { case 'u': if (!source.request(4)) { throw new EOFException("Unterminated escape sequence at path " + getPath()); byte c = buffer.getByte(i); result <<= 4; if (c >= '0' && c <= '9') { result += (c - 'A' + 10); } else { throw syntaxError("\\u" + buffer.readUtf8(4));
synchronized (Http2Stream.this) { finished = this.finished; flowControlError = byteCount + readBuffer.size() > maxByteCount; in.skip(byteCount); closeLater(ErrorCode.FLOW_CONTROL_ERROR); return; in.skip(byteCount); return; long read = in.read(receiveBuffer, byteCount); if (read == -1) throw new EOFException(); byteCount -= read; boolean wasEmpty = readBuffer.size() == 0; readBuffer.writeAll(receiveBuffer); if (wasEmpty) { Http2Stream.this.notifyAll();
while (pos < limit && !source.exhausted()) { int tagAndFieldEncoding = internalReadVarint32(); if (tagAndFieldEncoding == 0) throw new ProtocolException("Unexpected tag 0"); int tag = tagAndFieldEncoding >> TAG_FIELD_ENCODING_BITS; int groupOrFieldEncoding = tagAndFieldEncoding & FIELD_ENCODING_MASK; case STATE_END_GROUP: if (tag == expectedEndTag) return; // Success! throw new ProtocolException("Unexpected end group"); case STATE_LENGTH_DELIMITED: int length = internalReadVarint32(); pos += length; source.skip(length); break; case STATE_VARINT: break; default: throw new ProtocolException("Unexpected field encoding: " + groupOrFieldEncoding); throw new EOFException();
while (pos < limit && !source.exhausted()) { int tagAndFieldEncoding = internalReadVarint32(); if (tagAndFieldEncoding == 0) throw new ProtocolException("Unexpected tag 0"); throw new ProtocolException("Unexpected end group"); state = STATE_LENGTH_DELIMITED; int length = internalReadVarint32(); if (length < 0) throw new ProtocolException("Negative length: " + length); if (pushedLimit != -1) throw new IllegalStateException(); if (limit > pushedLimit) throw new EOFException(); return tag;
@Override public long read(Buffer sink, long byteCount) throws IOException { if (closed) throw new IOException("closed"); if (messageClosed) throw new IllegalStateException("closed"); if (frameBytesRead == frameLength) { if (isFinalFrame) return -1; // We are exhausted and have no continuations. readUntilNonControlFrame(); if (opcode != OPCODE_CONTINUATION) { throw new ProtocolException("Expected continuation opcode. Got: " + toHexString(opcode)); } if (isFinalFrame && frameLength == 0) { return -1; // Fast-path for empty final frame. } } long toRead = Math.min(byteCount, frameLength - frameBytesRead); long read; if (isMasked) { toRead = Math.min(toRead, maskBuffer.length); read = source.read(maskBuffer, 0, (int) toRead); if (read == -1) throw new EOFException(); toggleMask(maskBuffer, read, maskKey, frameBytesRead); sink.write(maskBuffer, 0, (int) read); } else { read = source.read(sink, toRead); if (read == -1) throw new EOFException(); } frameBytesRead += read; return read; }
logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); logger.log(buffer.readString(charset)); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " logger.log("<-- END HTTP (encoded body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); logger.log(buffer.clone().readString(charset));
logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " logger.log("<-- END HTTP (encoded body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.getBuffer(); gzippedLength = buffer.size(); try (GzipSource gzippedResponseBody = new GzipSource(buffer.clone())) { buffer = new Buffer(); MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8);
@Test public void skipTracksBufferFirst() throws Exception { Buffer source = new Buffer(); source.writeUtf8("bb"); BufferedSource bufferedSource = Okio.buffer((Source) source); bufferedSource.getBuffer().writeUtf8("aa"); bufferedSource.skip(2); assertEquals(0, bufferedSource.getBuffer().size()); assertEquals(2, source.size()); }
@Test public void writableChannelNioFile() throws Exception { File file = temporaryFolder.newFile(); FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE); testWritableByteChannel(fileChannel); BufferedSource emitted = Okio.buffer(Okio.source(file)); assertEquals("defghijklmnopqrstuvw", emitted.readUtf8()); emitted.close(); }
BufferedSource source = getNativeSource(new Buffer(), bodyGzipped(request.headers())); Buffer buffer = source.buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; transaction.setResponseMessage(response.message()); transaction.setResponseContentLength(responseBody.contentLength()); if (responseBody.contentType() != null) { transaction.setResponseContentType(responseBody.contentType().toString()); if (HttpHeaders.hasBody(response) && transaction.responseBodyIsPlainText()) { BufferedSource source = getNativeSource(response); source.request(Long.MAX_VALUE); Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); transaction.setResponseBody(readFromBuffer(buffer.clone(), charset)); } else { transaction.setResponseBodyIsPlainText(false); transaction.setResponseContentLength(buffer.size());
static ResponseBody cloneResponseBody(ResponseBody responseBody) { try { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); return ResponseBody.create(responseBody.contentType(), responseBody.contentLength(), source.buffer().clone()); } catch (IOException e) { throw new RuntimeException("Failed to read response body", e); } } }
int socksVersion = fromSource.readByte() & 0xff; if (socksVersion != VERSION_5) throw new ProtocolException(); int methodCount = fromSource.readByte() & 0xff; boolean foundSupportedMethod = false; for (int i = 0; i < methodCount; i++) { int method = fromSource.readByte() & 0xff; foundSupportedMethod |= method == METHOD_NO_AUTHENTICATION_REQUIRED; if (!foundSupportedMethod) throw new ProtocolException(); int version = fromSource.readByte() & 0xff; int command = fromSource.readByte() & 0xff; int reserved = fromSource.readByte() & 0xff; if (version != VERSION_5 || command != COMMAND_CONNECT || reserved != 0) { throw new ProtocolException(); int addressType = fromSource.readByte() & 0xff; InetAddress inetAddress; if (addressType == ADDRESS_TYPE_IPV4) { inetAddress = InetAddress.getByAddress(fromSource.readByteArray(4L)); } else if (addressType == ADDRESS_TYPE_DOMAIN_NAME){ int domainNameLength = fromSource.readByte() & 0xff; inetAddress = InetAddress.getByName(fromSource.readUtf8(domainNameLength)); } else { throw new ProtocolException(); int port = fromSource.readShort() & 0xffff;