List of usage examples for com.squareup.okhttp Request httpUrl
public HttpUrl httpUrl()
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 ww .j av a2s .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() + ' ' + 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
@Override public Request authenticate(Proxy proxy, Response response) throws IOException { Request request = response.request(); if (host != null && !request.httpUrl().host().equalsIgnoreCase(host)) { Constants.log.warn("Not authenticating against " + host + " for security reasons!"); return null; }/*from www . j a v a 2s.c o m*/ // check whether this is the first authentication try with our credentials Response priorResponse = response.priorResponse(); boolean triedBefore = priorResponse != null ? priorResponse.request().header(HEADER_AUTHORIZATION) != null : false; HttpUtils.AuthScheme basicAuth = null, digestAuth = null; for (HttpUtils.AuthScheme scheme : HttpUtils .parseWwwAuthenticate(response.headers(HEADER_AUTHENTICATE).toArray(new String[0]))) if ("Basic".equalsIgnoreCase(scheme.name)) basicAuth = scheme; else if ("Digest".equalsIgnoreCase(scheme.name)) digestAuth = scheme; // we MUST prefer Digest auth [https://tools.ietf.org/html/rfc2617#section-4.6] if (digestAuth != null) { // Digest auth if (triedBefore && !"true".equalsIgnoreCase(digestAuth.params.get("stale"))) // credentials didn't work last time, and they won't work now -> stop here return null; return authorizationRequest(request, digestAuth); } else if (basicAuth != null) { // Basic auth if (triedBefore) // credentials didn't work last time, and they won't work now -> stop here return null; return request.newBuilder().header(HEADER_AUTHORIZATION, Credentials.basic(username, password)).build(); } // no supported auth scheme return null; }
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;// w ww .ja v a 2 s .c o 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:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void buildRequestUsingHttpUrl() throws Exception { server.enqueue(new MockResponse()); HttpUrl httpUrl = HttpUrl.get(server.getUrl("/")); Request request = new Request.Builder().url(httpUrl).build(); assertEquals(httpUrl, request.httpUrl()); FiberOkHttpTestUtil.executeInFiberRecorded(client, request).assertSuccessful(); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
private void asyncInterceptors(List<Interceptor> interceptors) throws Exception { server.enqueue(new MockResponse()); interceptors.add(new Interceptor() { @Override/* w w w . j a v a 2s .c o m*/ public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder().addHeader("OkHttp-Intercepted", "yep").build(); } }); Request request = new Request.Builder().url(server.url("/")).build(); client.newCall(request).enqueue(callback); callback.await(request.httpUrl()).assertCode(200).assertHeader("OkHttp-Intercepted", "yep"); }
From source file:co.paralleluniverse.fibers.okhttp.test.InterceptorTest.java
License:Apache License
/** Make sure interceptors can interact with the OkHttp client asynchronously. */ @Test//ww w.j av a 2s . com public void interceptorMakesAnUnrelatedAsyncRequest() throws Exception { server.enqueue(new MockResponse().setBody("a")); // Fetched by interceptor. server.enqueue(new MockResponse().setBody("b")); // Fetched directly. client.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { if (chain.request().url().getPath().equals("/b")) { Request requestA = new Request.Builder().url(server.url("/a")).build(); try { RecordingCallback callbackA = new RecordingCallback(); client.newCall(requestA).enqueue(callbackA); callbackA.await(requestA.httpUrl()).assertBody("a"); } catch (Exception e) { throw new RuntimeException(e); } } return chain.proceed(chain.request()); } }); Request requestB = new Request.Builder().url(server.url("/b")).build(); RecordingCallback callbackB = new RecordingCallback(); client.newCall(requestB).enqueue(callbackB); callbackB.await(requestB.httpUrl()).assertBody("b"); }
From source file:com.anony.okhttp.sample.LoggingInterceptors.java
License:Apache License
public LoggingInterceptors() { client.networkInterceptors().add(new Interceptor() { @Override/* ww w. ja v a2s . c o m*/ 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
@Override public void after(Object target, Object[] args, Object result, Throwable throwable) { if (isDebug) { logger.afterInterceptor(target, args); }/*from www.java2 s. c o m*/ final Trace trace = traceContext.currentTraceObject(); if (trace == null) { return; } if (!validate(target)) { return; } try { SpanEventRecorder recorder = trace.currentSpanEventRecorder(); recorder.recordApi(methodDescriptor); recorder.recordException(throwable); Request request = ((UserRequestGetter) target)._$APM$_getUserRequest(); if (request != null) { recorder.recordAttribute(AnnotationKey.HTTP_URL, request.httpUrl().toString()); final String endpoint = getDestinationId(request.httpUrl()); recorder.recordDestinationId(endpoint); recordRequest(trace, request, throwable); } // clear attachment. InterceptorGroupInvocation invocation = interceptorGroup.getCurrentInvocation(); if (invocation != null && invocation.getAttachment() != null) { invocation.removeAttachment(); } } finally { trace.traceBlockEnd(); } }
From source file:com.dreamdigitizers.androidsoundcloudapi.core.Api.java
private Api(final String pClientId, final String pOauthToken) { OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.interceptors().add(new Interceptor() { @Override// ww w . j a va2 s . c o m public Response intercept(Chain pChain) throws IOException { Request request = pChain.request(); HttpUrl.Builder builder = request.httpUrl().newBuilder(); builder.addQueryParameter("client_id", pClientId); if (!TextUtils.isEmpty(pOauthToken)) { builder.addQueryParameter("oauth_token", pOauthToken); } HttpUrl httpUrl = builder.build(); Log.d(Api.TAG, httpUrl.url().toString()); request = request.newBuilder().url(httpUrl).build(); Response response = pChain.proceed(request); String bodyString = response.body().string(); response = response.newBuilder() .body(ResponseBody.create(response.body().contentType(), bodyString)).build(); Log.d(Api.TAG, bodyString); return response; } }); Retrofit retrofit = new Retrofit.Builder().baseUrl(IApi.API_URL__BASE).client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); this.mApi = retrofit.create(IApi.class); }
From source file:com.ibm.watson.developer_cloud.service.RequestBuilderTest.java
License:Open Source License
/** * Test with query map of string object. *//*from www . ja va2 s . c o m*/ @Test public void testWithQueryMapOfStringObject() { final Map<String, Object> queryParams = new HashMap<String, Object>(); queryParams.put("p2", "p2"); queryParams.put("foo", "bar"); final Request request = RequestBuilder.post(url).withQueryMap(queryParams).build(); assertEquals("p2=p2&foo=bar", request.httpUrl().query()); }