List of usage examples for com.squareup.okhttp Request header
public String header(String name)
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); }/*w ww . ja v a 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; }
From source file:com.magnet.max.android.rest.RequestInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Log.i(TAG, "---------Intercepting url : " + request.method() + " " + request.urlString()); CallOptions options = requestManager.popRequestOptions(request); boolean isCacheEnabled = null != options && null != options.getCacheOptions(); if (isCacheEnabled) { if (options.getCacheOptions().isAlwaysUseCacheIfOffline() && ConnectivityManager.getInstance() .getConnectivityStatus() == ConnectivityManager.TYPE_NOT_CONNECTED) { Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions()); if (null != cachedResponse) { Log.d(TAG, "-------return from cache when isAlwaysUseCacheIfOffline==true and offline"); return cachedResponse; } else { throw new IOException("It's offline and no cached response found"); }// w w w .j a v a2 s . c o m } else if (options.getCacheOptions().getMaxCacheAge() > 0) { // Return from cache if it's not expired Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions()); if (null != cachedResponse) { Log.d(TAG, "-------return from cache when maxCacheAge = " + options.getCacheOptions().getMaxCacheAge()); return cachedResponse; } } } //Add auth token for network call String token = null; if ((authTokenProvider.isAuthEnabled() && authTokenProvider.isAuthRequired(request)) && (null != authTokenProvider.getAppToken() || null != authTokenProvider.getUserToken())) { String existingToken = request.header(AuthUtil.AUTHORIZATION_HEADER); if (null != existingToken && existingToken.startsWith("Basic")) { // Already has Basic Auth header, don't overwrite } else { token = getToken(); } } boolean useMock = false; if (null != options) { if (isCacheEnabled) { useMock = options.getCacheOptions().useMock(); } else if (null != options.getReliableCallOptions()) { useMock = options.getReliableCallOptions().useMock(); } } Response response = null; long startTime = System.currentTimeMillis(); try { // Modify request if (null != token || useMock) { Request.Builder newRequestBuilder = chain.request().newBuilder(); if (null != token) { newRequestBuilder.header(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(token)); } if (useMock) { newRequestBuilder.url(request.urlString().replace(RestConstants.REST_BASE_PATH, RestConstants.REST_MOCK_BASE_PATH)); } response = chain.proceed(newRequestBuilder.build()); } else { response = chain.proceed(request); } if (null != options && options.isReliable()) { // Reliable call requestManager.removeReliableRequest(request); } } catch (IOException e) { //if(null != options && options.isReliable()) { // Reliable call // requestManager.saveReliableRequest(request, null, null, options.getReliableCallOptions(), e.getMessage()); // //TODO : // return null; // Swallow exception //} else { // throw e; //} Log.e(TAG, "error when getting response", e); throw e; } Log.d(TAG, "---------Response for url : " + request.method() + " " + request.urlString() + " : code = " + response.code() + ", message = " + response.message() + " in " + (System.currentTimeMillis() - startTime) + " ms"); //Save/Update response in cache if (response.isSuccessful() && isCacheEnabled && (options.getCacheOptions().getMaxCacheAge() > 0 || options.getCacheOptions().isAlwaysUseCacheIfOffline())) { return cacheManager.cacheResponse(request, response, options.getCacheOptions()); } return response; }
From source file:com.microsoft.rest.UserAgentInterceptor.java
License:Open Source License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); String header = request.header("User-Agent"); if (header == null || header.equals(Version.userAgent()) || header.equals(DEFAULT_USER_AGENT_HEADER)) { request = chain.request().newBuilder().header("User-Agent", userAgent).build(); }/*from w w w . jav a 2s .c o m*/ return chain.proceed(request); }
From source file:com.planyourexchange.utils.TokenManagerTest.java
License:Open Source License
@Test(timeout = 1000) public void test_authenticate_before_success() throws Exception { final TokenManager tokenManager = new TokenManager(sharedPreferences); final AuthToken authToken = new AuthToken(); authToken.setToken("NICE TOKEN"); final Response response = new Response.Builder().protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://api.example.com").build()).code(404).build(); tokenManager.setTokenAction(new TokenManager.TokenAction() { @Override/* ww w .j a v a 2 s . c o m*/ public void newToken() { new Thread(new Runnable() { @Override public void run() { tokenManager.success(authToken, null); } }).start(); } }); new Thread(new Runnable() { @Override public void run() { try { Request result = tokenManager.authenticate(null, response); String header = result.header(AUTHORIZATION); assertEquals(TOKEN + authToken.getToken(), header); } catch (IOException e) { fail("Couldn't Authenticate"); } synchronized (LOCK) { LOCK.notifyAll(); } } }).start(); synchronized (LOCK) { LOCK.wait(); } }
From source file:com.spotify.apollo.http.client.HttpClient.java
License:Apache License
@Override public CompletionStage<com.spotify.apollo.Response<ByteString>> send(com.spotify.apollo.Request apolloRequest, Optional<com.spotify.apollo.Request> apolloIncomingRequest) { final Optional<RequestBody> requestBody = apolloRequest.payload().map(payload -> { final MediaType contentType = apolloRequest.header("Content-Type").map(MediaType::parse) .orElse(DEFAULT_CONTENT_TYPE); return RequestBody.create(contentType, payload); });/*from w w w . j a v a2 s . c o m*/ Headers.Builder headersBuilder = new Headers.Builder(); apolloRequest.headers().asMap().forEach((k, v) -> headersBuilder.add(k, v)); apolloIncomingRequest.flatMap(req -> req.header(AUTHORIZATION_HEADER)) .ifPresent(header -> headersBuilder.add(AUTHORIZATION_HEADER, header)); final Request request = new Request.Builder().method(apolloRequest.method(), requestBody.orElse(null)) .url(apolloRequest.uri()).headers(headersBuilder.build()).build(); final CompletableFuture<com.spotify.apollo.Response<ByteString>> result = new CompletableFuture<>(); //https://github.com/square/okhttp/wiki/Recipes#per-call-configuration OkHttpClient finalClient = client; if (apolloRequest.ttl().isPresent() && client.getReadTimeout() != apolloRequest.ttl().get().toMillis()) { finalClient = client.clone(); finalClient.setReadTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS); } finalClient.newCall(request).enqueue(TransformingCallback.create(result)); return result; }
From source file:com.spotify.apollo.http.server.HttpServerModuleTest.java
License:Apache License
@Test public void testParsesHeadersParameters() throws Exception { int port = 9085; try (Service.Instance instance = service().start(NO_ARGS, onPort(port))) { HttpServer server = HttpServerModule.server(instance); TestHandler testHandler = new TestHandler(); server.start(testHandler);// w w w .j av a 2 s. c o m Request httpRequest = new Request.Builder().get().url(baseUrl(port) + "/headers") .addHeader("Foo", "bar").addHeader("Repeat", "once").addHeader("Repeat", "twice").build(); com.squareup.okhttp.Response response = okHttpClient.newCall(httpRequest).execute(); assertThat(response.code(), is(IM_A_TEAPOT.code())); assertThat(testHandler.requests.size(), is(1)); final com.spotify.apollo.Request apolloRequest = testHandler.requests.get(0).request(); assertThat(apolloRequest.uri(), is("/headers")); assertThat(apolloRequest.header("Foo"), is(Optional.of("bar"))); assertThat(apolloRequest.header("Repeat"), is(Optional.of("once,twice"))); assertThat(apolloRequest.header("Baz"), is(Optional.empty())); System.out.println("apolloRequest.headers() = " + apolloRequest.headers()); } }
From source file:com.xing.api.Oauth1SigningInterceptorTest.java
License:Apache License
/** Asserts that the provided request contains an expected header, with provided oauth signature. */ private static void assertAuthHeader(Request request, String signature) { assertThat(request.header("Authorization")).isEqualTo("OAuth " + "oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", " + "oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", " + "oauth_signature=\"" + signature + "\", " + "oauth_signature_method=\"HMAC-SHA1\", " + "oauth_timestamp=\"1318622958\", " + "oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", " + "oauth_version=\"1.0\""); }
From source file:io.minio.Signer.java
License:Apache License
/** * Returns signed request object for given request, region, access key and secret key. *///from ww w .j a va 2 s . co m public static Request signV4(Request request, String region, String accessKey, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { String contentSha256 = request.header("x-amz-content-sha256"); DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date")); Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey); signer.setScope(); signer.setCanonicalRequest(); signer.setStringToSign(); signer.setSigningKey(); signer.setSignature(); signer.setAuthorization(); return request.newBuilder().header("Authorization", signer.authorization).build(); }
From source file:io.minio.Signer.java
License:Apache License
/** * Returns pre-signed HttpUrl object for given request, region, access key, secret key and expires time. *//*from w w w .ja v a 2s . c o m*/ public static HttpUrl presignV4(Request request, String region, String accessKey, String secretKey, int expires) throws NoSuchAlgorithmException, InvalidKeyException { String contentSha256 = "UNSIGNED-PAYLOAD"; DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date")); Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey); signer.setScope(); signer.setPresignCanonicalRequest(expires); signer.setStringToSign(); signer.setSigningKey(); signer.setSignature(); return signer.url.newBuilder() .addEncodedQueryParameter(encodeQueryString("X-Amz-Signature"), encodeQueryString(signer.signature)) .build(); }
From source file:it.smartcommunitylab.GzipRequestInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { return chain.proceed(originalRequest); }// w ww. j a v a2s .c o m Request compressedRequest = originalRequest.newBuilder().header("Content-Encoding", "gzip") .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))).build(); return chain.proceed(compressedRequest); }