List of usage examples for com.squareup.okhttp Request headers
Headers headers
To view the source code for com.squareup.okhttp Request headers.
Click Source Link
From source file:alberto.avengers.model.rest.utils.interceptors.HttpLoggingInterceptor.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); }//www . jav a2 s.com boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; 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() + ' ' + requestPath(request.httpUrl()) + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } String endMessage = "--> END " + request.method(); if (logBody && hasRequestBody) { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } logger.log(""); logger.log(buffer.readString(charset)); endMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(endMessage); } long startNs = System.nanoTime(); Response response = chain.proceed(request); long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); logger.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++) { logger.log(headers.name(i) + ": " + headers.value(i)); } String endMessage = "<-- END HTTP"; if (logBody) { 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 (responseBody.contentLength() != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } endMessage += " (" + buffer.size() + "-byte body)"; } logger.log(endMessage); } return response; }
From source file:at.bitfire.dav4android.exception.HttpException.java
License:Open Source License
public HttpException(Response response) { super(response.code() + " " + response.message()); status = response.code();/* w w w. j a v a2s . co m*/ message = response.message(); /* As we don't know the media type and character set of request and response body, only printable ASCII characters will be shown in clear text. Other octets will be shown as "[xx]" where xx is the hex value of the octet. */ // format request Request request = response.request(); StringBuilder formatted = new StringBuilder(); formatted.append(request.method() + " " + request.urlString() + "\n"); Headers headers = request.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (request.body() != null) try { formatted.append("\n"); Buffer buffer = new Buffer(); request.body().writeTo(buffer); while (!buffer.exhausted()) appendByte(formatted, buffer.readByte()); } catch (IOException e) { } this.request = formatted.toString(); // format response formatted = new StringBuilder(); formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n"); headers = response.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (response.body() != null) try { formatted.append("\n"); for (byte b : response.body().bytes()) appendByte(formatted, b); } catch (IOException e) { } this.response = formatted.toString(); }
From source file:cn.com.canon.darwin.modules.service.api.interceptor.HttpLoggingInterceptor.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 www. j ava 2s. com*/ boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; 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.url() + ' ' + protocol; if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.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) { // logger.log("Content-Type: " + requestBody.contentType()); // } // if (requestBody.contentLength() != -1) { // logger.log("Content-Length: " + requestBody.contentLength()); // } // } // Headers headers = request.headers(); // for (int i = 0, count = headers.size(); i < count; i++) { // String name = headers.name(i); // // Skip headers from the request body as they are explicitly // // logged above. // if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { // logger.log(name + ": " + headers.value(i)); // } // } if (!logBody || !hasRequestBody) { logger.log("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { logger.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) { charset = contentType.charset(UTF8); } logger.log(""); if (isPlaintext(buffer)) { logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)"); } } } long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')'); // if (logHeaders) { // Headers headers = response.headers(); // for (int i = 0, count = headers.size(); i < count; i++) { // logger.log(headers.name(i) + ": " + headers.value(i)); // } // if (!logBody || !HttpEngine.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyEncoded(response.headers())) { 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(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { logger.log(""); logger.log("Couldn't decode the response body; charset is likely malformed."); logger.log("<-- END HTTP"); return response; } } if (!isPlaintext(buffer)) { logger.log(""); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; } if (contentLength != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } logger.log("<-- END HTTP (" + buffer.size() + "-byte body)"); } // } return response; }
From source file:com.anony.okhttp.sample.LoggingInterceptors.java
License:Apache License
public LoggingInterceptors() { client.networkInterceptors().add(new Interceptor() { @Override/*from w w w . j a v a2s. c om*/ public Response intercept(Chain chain) throws IOException { long t1 = System.nanoTime(); Request request = chain.request(); logger.info(String.format("Sending request %s on %s%n%s", request.httpUrl(), chain.connection(), request.headers())); Response response = chain.proceed(request); long t2 = System.nanoTime(); logger.info(String.format("Received response for %s in %.1fms%n%s", request.httpUrl(), (t2 - t1) / 1e6d, response.headers())); return response; } }); }
From source file:com.baidu.oped.apm.plugin.okhttp.interceptor.HttpEngineSendRequestMethodInterceptor.java
License:Apache License
private void recordCookie(Request request, Trace trace) { for (String cookie : request.headers("Cookie")) { if (cookieSampler.isSampling()) { final SpanEventRecorder recorder = trace.currentSpanEventRecorder(); recorder.recordAttribute(AnnotationKey.HTTP_COOKIE, StringUtils.drop(cookie, 1024)); }/* www . java 2 s .c om*/ return; } }
From source file:com.carlospinan.demoretrofit2.helpers.LoggingInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); Log.d(LOG_TAG, String.format("--> Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); Buffer requestBuffer = new Buffer(); if (request.body() != null) { request.body().writeTo(requestBuffer); Log.d(LOG_TAG, requestBuffer.readUtf8()); }// w ww.j av a 2 s .c om Response response = chain.proceed(request); long t2 = System.nanoTime(); Log.d(LOG_TAG, String.format("<-- Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); MediaType contentType = response.body().contentType(); String content = response.body().string(); Log.d(LOG_TAG, content); ResponseBody wrappedBody = ResponseBody.create(contentType, content); return response.newBuilder().body(wrappedBody).build(); }
From source file:com.cml.rx.android.api.HttpLoggingInterceptor.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 ww . j ava 2s. c o m boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; 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.url() + ' ' + protocol; if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.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) { logger.log("Content-Type: " + requestBody.contentType()); } if (requestBody.contentLength() != -1) { logger.log("Content-Length: " + requestBody.contentLength()); } } Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); // Skip headers from the request body as they are explicitly // logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { logger.log(name + ": " + headers.value(i)); } } if (!logBody || !hasRequestBody) { logger.log("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { logger.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) { charset = contentType.charset(UTF8); } logger.log(""); if (isPlaintext(buffer)) { logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)"); } } } long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } if (!logBody || !HttpEngine.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyEncoded(response.headers())) { 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(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { logger.log(""); logger.log("Couldn't decode the response body; charset is likely malformed."); logger.log("<-- END HTTP"); return response; } } if (!isPlaintext(buffer)) { logger.log(""); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; } if (contentLength != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } logger.log("<-- END HTTP (" + buffer.size() + "-byte body)"); } } return response; }
From source file:com.frostwire.http.HttpClient.java
License:Open Source License
private com.squareup.okhttp.Request buildReq(Request request) { return new com.squareup.okhttp.Request.Builder().method(request.method().toString(), buildReqBody(request)) .headers(Headers.of(request.headers())).url(request.url()).build(); }
From source file:com.google.android.exoplayer.ext.okhttp.OkHttpDataSource.java
License:Apache License
@Override public long open(DataSpec dataSpec) throws HttpDataSourceException { this.dataSpec = dataSpec; this.bytesRead = 0; this.bytesSkipped = 0; Request request = makeRequest(dataSpec); try {//from w w w.ja v a2s. c o m response = okHttpClient.newCall(request).execute(); responseByteStream = response.body().byteStream(); } catch (IOException e) { throw new HttpDataSourceException("Unable to connect to " + dataSpec.uri.toString(), e, dataSpec); } int responseCode = response.code(); // Check for a valid response code. if (!response.isSuccessful()) { Map<String, List<String>> headers = request.headers().toMultimap(); closeConnectionQuietly(); throw new InvalidResponseCodeException(responseCode, headers, dataSpec); } // Check for a valid content type. String contentType = response.body().contentType().toString(); if (contentTypePredicate != null && !contentTypePredicate.evaluate(contentType)) { closeConnectionQuietly(); throw new InvalidContentTypeException(contentType, dataSpec); } // If we requested a range starting from a non-zero position and received a 200 rather than a // 206, then the server does not support partial requests. We'll need to manually skip to the // requested position. bytesToSkip = responseCode == 200 && dataSpec.position != 0 ? dataSpec.position : 0; // Determine the length of the data to be read, after skipping. try { long contentLength = response.body().contentLength(); bytesToRead = dataSpec.length != C.LENGTH_UNBOUNDED ? dataSpec.length : contentLength != -1 ? contentLength - bytesToSkip : C.LENGTH_UNBOUNDED; } catch (IOException e) { closeConnectionQuietly(); throw new HttpDataSourceException(e, dataSpec); } opened = true; if (listener != null) { listener.onTransferStart(); } return bytesToRead; }
From source file:com.magnet.max.android.MaxRestAuthenticator.java
License:Apache License
@Override public Request authenticate(Proxy proxy, Response response) throws IOException { Request request = response.request(); String originalToken = AuthUtil.extractOAuthToken(request.header(AuthUtil.AUTHORIZATION_HEADER)); String authError = response.header(Response401.ERROR_HEADER); Log.e(TAG, "Got 401 for request : " + request.urlString() + " with token :\n" + originalToken + "\n error : " + authError); Response401 response401 = null; if (StringUtil.isNotEmpty(authError)) { response401 = new Response401(authError); }/*ww w. j a va 2 s. c o m*/ final AtomicReference<String> refreshedToken = new AtomicReference<>(); String requestPath = request.httpUrl().encodedPath(); if (requestPath.endsWith("/")) { requestPath = requestPath.substring(0, requestPath.length() - 1); } if (requestPath.endsWith(RestConstants.APP_LOGIN_URL) || requestPath.endsWith(RestConstants.APP_LOGIN_WITH_DEVICE_URL)) { // App login failed, handle by callback in MagnetRestAdapter } else if (requestPath.endsWith(RestConstants.USER_LOGIN_URL) || requestPath.endsWith(RestConstants.USER_LOGOUT_URL)) { // User login failed, handle by callback in User.login } else if (requestPath.endsWith(RestConstants.USER_REFRESH_TOKEN_URL)) { // User token refresh failed MaxCore.userTokenInvalid(originalToken, null); } else if (null != response401 && response401.getErrorType() == Response401.AuthErrorType.CLIENT_ACCESS_TOKEN) { renewAppToken(refreshedToken); } else if (null != response401 && response401.getErrorType() == Response401.AuthErrorType.USER_ACCESS_TOKEN) { renewUserToken(refreshedToken); } else { if (null != response401) { if (response401.getErrorType() == Response401.AuthErrorType.USER_ACCESS_TOKEN) { MaxCore.userTokenInvalid(originalToken, null); } else { MaxCore.appTokenInvalid(originalToken, null); } } else { MaxCore.tokenInvalid(originalToken, null); } } // Reply the request with refreshed token if (null != refreshedToken.get()) { Log.d(TAG, "Using refreshed token : " + refreshedToken.get()); // Replace token Headers newHeaders = request.headers().newBuilder() .set(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(refreshedToken.get())).build(); return request.newBuilder().headers(newHeaders).build(); } else { Log.w(TAG, "No new token available, won't answer the challenge for " + request.urlString()); } return null; }