List of usage examples for com.squareup.okhttp Response request
Request request
To view the source code for com.squareup.okhttp Response request.
Click Source Link
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 w w .j a v a 2 s .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.cuddlesoft.norilib.clients.Danbooru.java
/** * Create a new Danbooru 1.x client with authentication. * * @param name Human-readable service name. * @param endpoint URL to the HTTP API Endpoint - the server implementing the API. * @param username Username used for authentication. * @param apiKey API key used for authentication. *///from ww w . jav a 2s . c om public Danbooru(String name, String endpoint, String username, final String apiKey) { this.name = name; this.apiEndpoint = endpoint; this.username = username; this.apiKey = apiKey; // Enable HTTP Basic Authentication. okHttpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { final String credential = Base64.encodeToString( String.format("%s:%s", Danbooru.this.username, Danbooru.this.apiKey).getBytes(), Base64.DEFAULT); return response.request().newBuilder().header("Authorization", credential).build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); }
From source file:com.cuddlesoft.norilib.clients.DanbooruLegacy.java
/** * Create a new Danbooru 1.x client with authentication. * * @param endpoint URL to the HTTP API Endpoint - the server implementing the API. * @param username Username used for authentication. * @param password Password used for authentication. *///from w w w. ja v a 2s .c o m public DanbooruLegacy(String name, String endpoint, String username, String password) { this.name = name; this.apiEndpoint = endpoint; this.username = username; this.password = password; // Enable HTTP basic authentication. okHttpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { final String credential = Credentials.basic(DanbooruLegacy.this.username, DanbooruLegacy.this.password); return response.request().newBuilder().header("Authorization", credential).build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); }
From source file:com.digi.wva.internal.HttpClient.java
License:Mozilla Public License
/** * Wrap an HttpCallback in an OkHttp {@link Callback} instance. * Also will automatically attempt to parse the response as JSON. * * <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://from w w w . ja v a 2 s . co m * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a> * </p> * @param callback the {@link com.digi.wva.internal.HttpClient.HttpCallback} to wrap * @return a corresponding {@link Callback} */ protected Callback wrapCallback(final HttpCallback callback) { return new Callback() { @Override public void onResponse(Response response) throws IOException { logResponse(response); Request request = response.request(); String responseBody = response.body().string(); if (response.isSuccessful()) { // Request succeeded. Parse JSON response. try { JSONObject parsed = new JSONObject(responseBody); callback.onSuccess(parsed); } catch (JSONException e) { callback.onJsonParseError(e, responseBody); } } else { int status = response.code(); String url = response.request().urlString(); Exception error; // Generate an appropriate exception based on the status code switch (status) { case 400: error = new WvaHttpBadRequest(url, responseBody); break; case 403: error = new WvaHttpForbidden(url, responseBody); break; case 404: error = new WvaHttpNotFound(url, responseBody); break; case 414: error = new WvaHttpRequestUriTooLong(url, responseBody); break; case 500: error = new WvaHttpInternalServerError(url, responseBody); break; case 503: error = new WvaHttpServiceUnavailable(url, responseBody); break; default: error = new WvaHttpException("HTTP " + status, url, responseBody); break; } callback.onFailure(error); } } @Override public void onFailure(Request request, IOException exception) { callback.onFailure(exception); } }; }
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:/* w w w . java 2 s .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.digi.wva.internal.HttpClientTest.java
License:Mozilla Public License
/** * Just for code coverage over the request/response logging and basic "is it working" test. * This will cover the code branches where the prior request was NOT a redirect. *//*from www . ja v a 2 s . c o m*/ public void testAuthChallenge() { dut.setLoggingEnabled(true); // First send an auth challenge server.enqueue( new MockResponse().addHeader("WWW-Authenticate", "Basic realm=\"foo\"").setResponseCode(401)); // Then send an OK response server.enqueue(new MockResponse().setResponseCode(200).setBody("{}")); // Need to set up an Authenticator to handle the challenge though. But as was mentioned above, // this test is purely to exercise the code for a) coverage and b) assurance that it doesn't // error out in this case. dut.getUnderlyingClient().setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { // See https://github.com/square/okhttp/wiki/Recipes, "Handling authentication" String credentials = com.squareup.okhttp.Credentials.basic("user", "pass"); return response.request().newBuilder().header("Authorization", credentials).build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); dut.get("some_url", callback); PassFailHttpCallback.RecordedResponse r = callback.await(); assertTrue(r.success); assertNull(r.error); }
From source file:com.github.mmatczuk.ablb.benchmark.OkHttpAsync.java
License:Apache License
@Override public void prepare(final Benchmark benchmark) { concurrencyLevel = benchmark.concurrencyLevel; targetBacklog = benchmark.targetBacklog; client = new OkHttpClient(); client.setDispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel, benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()))); callback = new Callback() { @Override/*from ww w. j a v a2 s . c o m*/ public void onFailure(Request request, IOException e) { System.out.println("Failed: " + e); } @Override public void onResponse(Response response) throws IOException { ResponseBody body = response.body(); long total = readAllAndClose(body.byteStream()); long finish = System.nanoTime(); if (VERBOSE) { long start = (Long) response.request().tag(); System.out.printf("Transferred % 8d bytes in %4d ms%n", total, TimeUnit.NANOSECONDS.toMillis(finish - start)); } requestsInFlight.decrementAndGet(); } }; }
From source file:com.github.radium226.github.maven.AssetWagon.java
License:Apache License
@Override public void doConnect(Optional<AuthenticationInfo> authenticationInfo) throws ConnectionException { try {/* ww w. ja v a2 s . com*/ // GitHub Authentication GitHubBuilder gitHubBuilder = new GitHubBuilder(); if (authenticationInfo.isPresent()) { String login = authenticationInfo.get().getUserName(); String password = authenticationInfo.get().getPassword(); if (password.startsWith("oauth2_token:")) { gitHubBuilder = gitHubBuilder.withOAuthToken(password.substring("oauth2_otken:".length())); } else { gitHubBuilder = gitHubBuilder.withPassword(login, password); } } // Proxy Authentication okHttpClient = new OkHttpClient(); ProxyInfo proxyInfo = getProxyInfoByType("http"); if (proxyInfo != null) { okHttpClient.setProxy(ProxyInfos.asProxy(proxyInfo)); final String userName = proxyInfo.getUserName(); final String password = proxyInfo.getPassword(); if (userName != null && password != null) { okHttpClient.setAuthenticator(new Authenticator() { @Override public Request authenticateProxy(Proxy proxy, Response response) { return response.request(); } @Override public Request authenticate(Proxy proxy, Response response) throws IOException { String credentials = Credentials.basic(userName, password); return response.request().newBuilder().header("Proxy-Authorization", credentials) .build(); } }); } } gitHub = gitHubBuilder.withConnector(new OkHttpConnector(new OkUrlFactory(okHttpClient))).build(); this.gitHubService = GitHubService.forGitHub(gitHub).withHttpClient(okHttpClient); GHMyself myself = gitHub.getMyself(); LOGGER.info("Connected as {}", myself.getName()); } catch (IOException e) { throw new ConnectionException("Unable to connect to GitHub", e); } }
From source file:com.groupon.mesos.util.HttpProtocolSender.java
License:Apache License
@Override public void onResponse(final Response response) throws IOException { final Object tag = response.request().tag(); checkState(tag != null, "saw a request with null tag"); final SettableFuture<Void> future = inFlight.remove(tag); checkState(future != null, "Saw tag %s but not in in flight map", tag); future.set(null);/* w w w . ja va 2 s . com*/ LOG.debug("Response %s %s: %d", response.request().method(), response.request().urlString(), response.code()); }
From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java
License:Apache License
@Override public synchronized File downloadFile(@NonNull CFile file, @Nullable String filename) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/*from w w w .j a v a 2 s. c om*/ // assign filename if (TextUtils.isEmpty(filename)) filename = file.getName(); String fileId = file.getId(); Request request = new Request.Builder().url(API_BASE_URL + "/files/" + fileId + "/content") .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { switch (response.code()) { case 200: // redirect to url return downloadFile(response.request(), filename); case 202: // retry after due to file just uploaded delayDownloadFile(file, filename); break; case 302: // redirect to url return downloadFile(response.request(), filename); } } else { throw new RequestFailException(response.message(), response.code()); } } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } return null; }