List of usage examples for com.squareup.okhttp Request method
String method
To view the source code for com.squareup.okhttp Request method.
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); }//from w w w. j a v a 2 s.co 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() + ' ' + 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.BasicDigestAuthenticator.java
License:Open Source License
protected Request authorizationRequest(Request request, HttpUtils.AuthScheme digest) { String realm = digest.params.get("realm"), opaque = digest.params.get("opaque"), nonce = digest.params.get("nonce"); Algorithm algorithm = Algorithm.determine(digest.params.get("algorithm")); Protection qop = Protection.selectFrom(digest.params.get("qop")); // build response parameters String response = null;// www . jav a2s.co m List<String> params = new LinkedList<>(); params.add("username=" + quotedString(username)); if (realm != null) params.add("realm=" + quotedString(realm)); else return null; if (nonce != null) params.add("nonce=" + quotedString(nonce)); else return null; if (opaque != null) params.add("opaque=" + quotedString(opaque)); else return null; if (algorithm != null) params.add("algorithm=" + quotedString(algorithm.name)); final String method = request.method(); final String digestURI = request.httpUrl().encodedPath(); params.add("uri=" + quotedString(digestURI)); if (qop != null) { params.add("qop=" + qop.name); params.add("cnonce=" + quotedString(clientNonce)); int nc = nonceCount.getAndIncrement(); String ncValue = String.format("%08x", nc); params.add("nc=" + ncValue); String a1 = null; if (algorithm == Algorithm.MD5) a1 = username + ":" + realm + ":" + password; else if (algorithm == Algorithm.MD5_SESSION) a1 = h(username + ":" + realm + ":" + password) + ":" + nonce + ":" + clientNonce; //Constants.log.trace("A1=" + a1); String a2 = null; if (qop == Protection.Auth) a2 = method + ":" + digestURI; else if (qop == Protection.AuthInt) try { RequestBody body = request.body(); a2 = method + ":" + digestURI + ":" + (body != null ? h(body) : h("")); } catch (IOException e) { Constants.log.warn("Couldn't get entity-body for hash calculation"); } //Constants.log.trace("A2=" + a2); if (a1 != null && a2 != null) response = kd(h(a1), nonce + ":" + ncValue + ":" + clientNonce + ":" + qop.name + ":" + h(a2)); } else { //Constants.log.debug("Using legacy Digest auth"); // legacy (backwards compatibility with RFC 2069) if (algorithm == Algorithm.MD5) { String a1 = username + ":" + realm + ":" + password, a2 = method + ":" + digestURI; response = kd(h(a1), nonce + ":" + h(a2)); } } if (response != null) { params.add("response=" + quotedString(response)); return request.newBuilder().header(HEADER_AUTHORIZATION, "Digest " + TextUtils.join(", ", params)) .build(); } else return null; }
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();/*from w w w .j a v a 2 s .c o 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:bitrefill.retrofit.Generator.java
static void configAuth(OkHttpClient client, Config config) { final String auth = getAuth(config); if (auth == null) { return;// w w w . j a v a2 s . co m } client.interceptors().clear(); client.interceptors().add(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder().header("Authorization", "Basic " + auth) .header("Accept", "applicaton/json").method(original.method(), original.body()); Request request = requestBuilder.build(); return chain.proceed(request); } }); }
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 w w w . j a v a 2 s . co 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.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); }/* www . j a v a 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.davidecirillo.dashboard.data.RestService.java
License:Apache License
public void create() { final OkHttpClient client = new OkHttpClient(); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); if (BuildConfig.DEBUG) loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); else//from ww w . j a v a2 s . c o m loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE); List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(loggingInterceptor); interceptors.add(new LoggingInterceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request request = original.newBuilder().method(original.method(), original.body()).build(); return chain.proceed(request); } }); client.networkInterceptors().addAll(interceptors); retrofit.Retrofit restAdapterLocal = new retrofit.Retrofit.Builder().client(client) .baseUrl(AppConfig.http + mLocalUrl).addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); retrofit.Retrofit restAdapterRemote = new retrofit.Retrofit.Builder().client(client) .baseUrl(AppConfig.http + mRemoteUrl).addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); mLocalPiApi = restAdapterLocal.create(PIApi.class); mRemotePiApi = restAdapterRemote.create(PIApi.class); }
From source file:com.digi.wva.internal.HttpClient.java
License:Mozilla Public License
/** * Log information of OkHttp Request objects * * <p>This method is protected, rather than private, due to a bug between JaCoCo and * the Android build tools which causes the instrumented bytecode to be invalid when this * method is private:// w w w . j av a 2 s. com * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a> * </p> */ protected void logRequest(Request request) { if (!doLogging) { // Logging is disabled - do nothing. return; } Log.i(TAG, "\u2192 " + request.method() + " " + request.urlString()); }
From source file:com.digi.wva.internal.HttpClient.java
License:Mozilla Public License
/** * Log information of OkHttp Response objects * * <p>This method is protected, rather than private, due to a bug between JaCoCo and * the Android build tools which causes the instrumented bytecode to be invalid when this * method is private:// ww w. j a v a2s . com * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a> * </p> * @param response the HTTP response object to log */ protected void logResponse(Response response) { if (!doLogging) { // Logging is disabled - do nothing. return; } Request request = response.request(); StringBuilder log = new StringBuilder(); log.append( // e.g. <-- 200 GET /ws/hw/leds/foo String.format("\u2190 %d %s %s", response.code(), request.method(), request.urlString())); // Add on lines tracking any redirects that occurred. Response prior = response.priorResponse(); if (prior != null) { // Call out that there were prior responses. log.append(" (prior responses below)"); // Add a line to the log message for each prior response. // (For most if not all responses, there will likely be just one.) do { log.append(String.format("\n... prior response: %d %s %s", prior.code(), prior.request().method(), prior.request().urlString())); // If this is a redirect, log the URL we're being redirected to. if (prior.isRedirect()) { log.append(", redirecting to "); log.append(prior.header("Location", "[no Location header found?!]")); } prior = prior.priorResponse(); } while (prior != null); } Log.i(TAG, log.toString()); }
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(); }