List of usage examples for com.squareup.okhttp RequestBody writeTo
public abstract void writeTo(BufferedSink sink) throws IOException;
From source file:com.xing.api.CallSpecTest.java
License:Apache License
@Test public void builderAllowsRawBody() throws Exception { CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class) .body(RequestBody.create(MediaType.parse("application/text"), "Hey!")); // Build the CallSpec so that we can build the request. builder.build();//from w w w . j av a 2 s. c om Request request = builder.request(); RequestBody body = request.body(); assertThat(body.contentLength()).isEqualTo(4); assertThat(body.contentType().subtype()).isEqualTo("text"); Buffer buffer = new Buffer(); body.writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo("Hey!"); }
From source file:com.xing.api.CallSpecTest.java
License:Apache License
private static void assertRequestHasBody(Request request, TestMsg expected, int contentLength) throws IOException { RequestBody body = request.body(); assertThat(body.contentLength()).isEqualTo(contentLength); assertThat(body.contentType().subtype()).isEqualTo("json"); Buffer buffer = new Buffer(); body.writeTo(buffer); assertThat(buffer.readUtf8()).contains("\"msg\":\"" + expected.msg + '"') .contains("\"code\":" + expected.code).startsWith("{").endsWith("}").hasSize(contentLength); }
From source file:com.xing.api.Oauth1SigningInterceptor.java
License:Apache License
public Request signRequest(Request request) throws IOException { byte[] nonce = new byte[NUANCE_BYTES]; random.nextBytes(nonce);/*from www . j av a2 s .com*/ String oauthNonce = CHARACTER_PATTERN.matcher(ByteString.of(nonce).base64()).replaceAll(""); String oauthTimestamp = clock.millis(); String consumerKeyValue = UrlEscapeUtils.escape(consumerKey); String accessTokenValue = UrlEscapeUtils.escape(accessToken); SortedMap<String, String> parameters = new TreeMap<>(); parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue); parameters.put(OAUTH_ACCESS_TOKEN, accessTokenValue); parameters.put(OAUTH_NONCE, oauthNonce); parameters.put(OAUTH_TIMESTAMP, oauthTimestamp); parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE); parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE); HttpUrl url = request.httpUrl(); for (int i = 0; i < url.querySize(); i++) { parameters.put(UrlEscapeUtils.escape(url.queryParameterName(i)), UrlEscapeUtils.escape(url.queryParameterValue(i))); } Buffer body = new Buffer(); RequestBody requestBody = request.body(); if (requestBody != null) { requestBody.writeTo(body); } while (!body.exhausted()) { long keyEnd = body.indexOf((byte) '='); if (keyEnd == -1) { throw new IllegalStateException("Key with no value: " + body.readUtf8()); } String key = body.readUtf8(keyEnd); body.skip(1); // Equals. long valueEnd = body.indexOf((byte) '&'); String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd); if (valueEnd != -1) { body.skip(1); // Ampersand. } parameters.put(key, value); } Buffer base = new Buffer(); String method = request.method(); base.writeUtf8(method); base.writeByte('&'); base.writeUtf8(UrlEscapeUtils.escape(request.httpUrl().newBuilder().query(null).build().toString())); base.writeByte('&'); boolean first = true; for (Entry<String, String> entry : parameters.entrySet()) { if (!first) { base.writeUtf8(UrlEscapeUtils.escape("&")); } first = false; base.writeUtf8(UrlEscapeUtils.escape(entry.getKey())); base.writeUtf8(UrlEscapeUtils.escape("=")); base.writeUtf8(UrlEscapeUtils.escape(entry.getValue())); } String signingKey = UrlEscapeUtils.escape(consumerSecret) + '&' + UrlEscapeUtils.escape(accessSecret); SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1"); Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalStateException(e); } byte[] result = mac.doFinal(base.readByteArray()); String signature = ByteString.of(result).base64(); String authorization = "OAuth " // + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " // + OAUTH_NONCE + "=\"" + oauthNonce + "\", " // + OAUTH_SIGNATURE + "=\"" + UrlEscapeUtils.escape(signature) + "\", " // + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " // + OAUTH_TIMESTAMP + "=\"" + oauthTimestamp + "\", " // + OAUTH_ACCESS_TOKEN + "=\"" + accessTokenValue + "\", " // + OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + '"'; return request.newBuilder().addHeader("Authorization", authorization).build(); }
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); }/*from www .jav a2s . c o 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:io.macgyver.core.okhttp.LoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE || (!slf4j.isDebugEnabled())) { return chain.proceed(request); }/*from ww w. j av a2 s . c o m*/ boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; try { RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + request.httpUrl() + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } log(requestStartMessage); if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if (name.equalsIgnoreCase("authorization")) { log(name + ": ************"); } else { // Skip headers from the request body as they are // explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { log(name + ": " + headers.value(i)); } } } if (!logBody || !hasRequestBody) { slf4j.debug("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } log(""); String body = redactRequestBody(buffer.readString(charset)); log(body); log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace } long startNs = System.nanoTime(); Response response = chain.proceed(request); try { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " (" + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpEngine.hasBody(response)) { log("<-- END HTTP"); } else if (!isResponseBodyPrintable(response)) { log("<-- END HTTP (body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(maxPrintableBodySize); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() != 0) { log(""); log(redactResponseBody(buffer.clone().readString(charset))); } log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } } catch (Exception e) { LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString()); } return response; }
From source file:it.smartcommunitylab.GzipRequestInterceptor.java
License:Apache License
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { final Buffer buffer = new Buffer(); requestBody.writeTo(buffer); return new RequestBody() { @Override/*w w w .j a v a 2 s. com*/ public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() { return buffer.size(); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer.snapshot()); } }; }
From source file:it.smartcommunitylab.GzipRequestInterceptor.java
License:Apache License
private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override//from w w w.j a va 2s .co m public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; }
From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); }/*from w w w . ja v a 2s . c o m*/ boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; UUID requestId = UUID.randomUUID(); StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n') .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol); if (!logHeaders && requestBody != null) { requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)"); } requestMessage.append('\n'); if (logHeaders) { if (requestBody != null) { // Request body headers are only present when installed as a // network interceptor. Force // them to be included (when available) so there values are // known. if (requestBody.contentType() != null) { requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n'); } if (requestBody.contentLength() != -1) { requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n'); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name) || "Proxy-Authorization".equalsIgnoreCase(name) || "WWW-Authenticate".equalsIgnoreCase(name)) { requestMessage.append(name).append(": *****\n"); } // Skip headers from the request body as they are explicitly // logged above. else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { requestMessage.append(name).append(": ").append(headers.value(i)).append('\n'); } } if (!logBody || requestBody == null) { requestMessage.append("--> END ").append(requestId).append('\n'); } else if (bodyEncoded(request.headers())) { requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n'); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } requestMessage.append('\n'); if (isPlaintext(buffer)) { requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId) .append(" (").append(requestBody.contentLength()).append("-byte body)\n"); } else { requestMessage.append("--> END ").append(requestId).append(" (binary ") .append(requestBody.contentLength()).append("-byte body omitted)\n"); } } } logger.log(requestMessage.substring(0, requestMessage.length() - 1)); long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- " + requestId + "HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ') .append(response.request().url()).append(" (").append(tookMs).append("ms"); if (!logHeaders) { responseMessage.append(", "); if (contentLength != -1) { responseMessage.append(contentLength).append("-byte"); } else { responseMessage.append("unknown-length"); } responseMessage.append(" body"); } responseMessage.append(")\n"); responseMessage.append(response.code()).append(' ').append(response.message()).append('\n'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n'); } if (!logBody || !HttpEngine.hasBody(response)) { responseMessage.append("<-- END HTTP\n"); } else if (bodyEncoded(response.headers())) { responseMessage.append("<-- END HTTP (encoded body omitted)\n"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (!isPlaintext(buffer)) { responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size()) .append("-byte body omitted)"); logger.log(responseMessage.toString()); return response; } if (contentLength != 0) { responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n'); } responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n"); } } logger.log(responseMessage.substring(0, responseMessage.length() - 1)); return response; }