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:com.liferay.mobile.android.auth.basic.DigestAuthentication.java
License:Open Source License
@Override public Request authenticate(Proxy proxy, Response response) throws IOException { Request request = response.request(); Builder builder = request.newBuilder(); try {/*from w w w .j av a 2 s . co m*/ BasicHeader authenticateHeader = new BasicHeader(Headers.WWW_AUTHENTICATE, response.header(Headers.WWW_AUTHENTICATE)); DigestScheme scheme = new DigestScheme(); scheme.processChallenge(authenticateHeader); BasicHttpRequest basicHttpRequest = new BasicHttpRequest(request.method(), request.uri().getPath()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); String authorizationHeader = scheme.authenticate(credentials, basicHttpRequest).getValue(); builder.addHeader(Headers.AUTHORIZATION, authorizationHeader); } catch (Exception e) { throw new IOException(e); } return builder.build(); }
From source file:com.liferay.mobile.sdk.auth.DigestAuthentication.java
License:Open Source License
@Override public Request authenticate(Proxy proxy, Response response) throws IOException { Request request = response.request(); Builder builder = request.newBuilder(); try {// w w w . ja v a 2 s. c o m BasicHeader authenticateHeader = new BasicHeader(Headers.WWW_AUTHENTICATE, response.header(Headers.WWW_AUTHENTICATE)); DigestScheme scheme = new DigestScheme(); scheme.processChallenge(authenticateHeader); BasicHttpRequest basicHttpRequest = new BasicHttpRequest(request.method(), request.uri().getPath()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); String authorizationHeader = scheme.authenticate(credentials, basicHttpRequest).getValue(); builder.addHeader(Headers.AUTHORIZATION, authorizationHeader); } catch (Exception e) { throw new IOException(e); } return builder.build(); }
From source file:com.magnet.max.android.rest.qos.internal.CachedRequest.java
License:Apache License
public CachedRequest(Request request) { url = request.urlString();/* w w w. j av a2s . co m*/ method = request.method(); parseHeaders(request.headers()); if (null != request.body()) { try { Buffer buffer = new Buffer(); request.body().writeTo(buffer); body = CacheUtils.copyBody(buffer); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.magnet.max.android.rest.qos.internal.CacheManager.java
License:Apache License
public Response cacheResponse(Request request, Response response, CacheOptions options) { String requestHash = CacheUtils.getRequestHash(request); ResponseCacheEntity operation = findLatestCache(requestHash, request, options); long currentTimestamp = System.currentTimeMillis(); if (null == operation) { operation = new ResponseCacheEntity(); operation.createdAt = currentTimestamp; operation.url = request.urlString(); operation.httpMethod = request.method(); operation.requestHash = requestHash; operation.response = new CachedResponse(response); operation.responseCode = response.code(); operation.isOfflineCache = options.isAlwaysUseCacheIfOffline(); Log.d(TAG, "Adding cache for request " + request); } else {//w w w. j a v a2s. c o m //Update body operation.response = new CachedResponse(response); Log.d(TAG, "Updating cache for request " + request); } operation.updatedAt = currentTimestamp; long newExpiredTime = 0; if (options.getMaxCacheAge() > 0) { newExpiredTime = currentTimestamp + options.getMaxCacheAge() * 1000; } if (null == operation.getExpiredAt() || newExpiredTime > operation.getExpiredAt()) { operation.expiredAt = newExpiredTime; } operation.save(); if (null != response.body()) { return response.newBuilder() .body(ResponseBody.create(response.body().contentType(), operation.response.body)).build(); } else { return response; } }
From source file:com.magnet.max.android.rest.qos.internal.CacheUtils.java
License:Apache License
public static String getRequestHash(Request request) { StringBuilder sb = new StringBuilder(); //Method and URL sb.append(request.method()).append(request.urlString()); //Headers//from w w w.java 2s . c om if (null != request.headers()) { } //Body //Don't include body when it's multipart if (toHashBody(request)) { try { Buffer buffer = new Buffer(); Request copy = request.newBuilder().build(); copy.body().writeTo(buffer); sb.append(buffer.readUtf8()); } catch (IOException e) { e.printStackTrace(); } } return Util.md5Hex(sb.toString()); }
From source file:com.magnet.max.android.rest.qos.internal.ReliableManager.java
License:Apache License
public void saveRequest(Request request, ReliableCallOptions options, String reason) { String requestHash = CacheUtils.getRequestHash(request); ReliableRequestEntity operation = null; //findRequest(requestHash, request, options); long currentTimestamp = System.currentTimeMillis(); if (null == operation) { operation = new ReliableRequestEntity(); operation.createdAt = currentTimestamp; operation.url = request.urlString(); operation.httpMethod = request.method(); operation.requestHash = requestHash; operation.request = new CachedRequest(request); operation.options = options;/*from ww w . j a v a2 s .co m*/ operation.wifiPreq = hasPrerequisite(options.getConditions(), WifiCondition.class); Log.d(TAG, "Saving reliable request " + request); } else { //Update body Log.d(TAG, "Updating reliable request " + request); operation.retries = operation.retries + 1; } operation.updatedAt = currentTimestamp; long newExpiredTime = currentTimestamp + options.getExpiresIn() * 1000; if (null == operation.getExpiredAt() || newExpiredTime > operation.getExpiredAt()) { operation.expiredAt = newExpiredTime; } if (StringUtil.isNotEmpty(reason)) { operation.lastFailureReason = reason; } operation.lastFailureTime = currentTimestamp; operation.save(); }
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"); }//from w w w . j a v a 2 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.mamaspapas.api.helper.Oauth1SigningInterceptor.java
License:Apache License
public Request signRequest(Request request) throws IOException { byte[] nonce = new byte[32]; random.nextBytes(nonce);//from ww w .j av a 2s. co m String oauthNonce = ByteString.of(nonce).base64().replaceAll("\\W", ""); String oauthTimestamp = String.valueOf(clock.millis()); String consumerKeyValue = ESCAPER.escape(consumerKey); String accessTokenValue = ESCAPER.escape(accessToken); SortedMap<String, String> parameters = new TreeMap<>(); parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue); parameters.put(OAUTH_ACCESS_TOKEN, accessTokenValue); parameters.put(OAUTH_NONCE, oauthNonce); parameters.put(OAUTH_TIMESTAMP, oauthTimestamp); parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE); parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE); HttpUrl url = request.httpUrl(); for (int i = 0; i < url.querySize(); i++) { parameters.put(ESCAPER.escape(url.queryParameterName(i)), ESCAPER.escape(url.queryParameterValue(i))); } // RequestBody requestBody = request.body(); // Buffer body = new Buffer(); // requestBody.writeTo(body); // while (!body.exhausted()) { // long keyEnd = body.indexOf((byte) '='); // if (keyEnd == -1) throw new IllegalStateException("Key with no value: " + body.readUtf8()); // String key = body.readUtf8(keyEnd); // body.skip(1); // Equals. // // long valueEnd = body.indexOf((byte) '&'); // String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd); // if (valueEnd != -1) body.skip(1); // Ampersand. // // parameters.put(key, value); // } Buffer base = new Buffer(); String method = request.method(); base.writeUtf8(method); base.writeByte('&'); base.writeUtf8(ESCAPER.escape(request.httpUrl().newBuilder().query(null).build().toString())); base.writeByte('&'); boolean first = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (!first) base.writeUtf8(ESCAPER.escape("&")); first = false; base.writeUtf8(ESCAPER.escape(entry.getKey())); base.writeUtf8(ESCAPER.escape("=")); base.writeUtf8(ESCAPER.escape(entry.getValue())); } String signingKey = ESCAPER.escape(consumerSecret) + "&" + ESCAPER.escape(accessSecret); SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1"); Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalStateException(e); } byte[] result = mac.doFinal(base.readByteArray()); String signature = ByteString.of(result).base64(); String authorization = "OAuth " + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " + OAUTH_NONCE + "=\"" + oauthNonce + "\", " + OAUTH_SIGNATURE + "=\"" + ESCAPER.escape(signature) + "\", " + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " + OAUTH_TIMESTAMP + "=\"" + oauthTimestamp + "\", " + OAUTH_ACCESS_TOKEN + "=\"" + accessTokenValue + "\", " + OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + "\""; return request.newBuilder().addHeader("Authorization", authorization).build(); }
From source file:com.parse.ParseOkHttpClient.java
License:Open Source License
private ParseHttpRequest getParseHttpRequest(Request okHttpRequest) { ParseHttpRequest.Builder parseRequestBuilder = new ParseHttpRequest.Builder(); // Set method switch (okHttpRequest.method()) { case OKHTTP_GET: parseRequestBuilder.setMethod(ParseHttpRequest.Method.GET); break;//from w ww .j a v a 2 s. c om case OKHTTP_DELETE: parseRequestBuilder.setMethod(ParseHttpRequest.Method.DELETE); break; case OKHTTP_POST: parseRequestBuilder.setMethod(ParseHttpRequest.Method.POST); break; case OKHTTP_PUT: parseRequestBuilder.setMethod(ParseHttpRequest.Method.PUT); break; default: // This should never happen throw new IllegalArgumentException("Invalid http method " + okHttpRequest.method()); } // Set url parseRequestBuilder.setUrl(okHttpRequest.urlString()); // Set Header for (Map.Entry<String, List<String>> entry : okHttpRequest.headers().toMultimap().entrySet()) { parseRequestBuilder.addHeader(entry.getKey(), entry.getValue().get(0)); } // Set Body ParseOkHttpRequestBody okHttpBody = (ParseOkHttpRequestBody) okHttpRequest.body(); if (okHttpBody != null) { parseRequestBuilder.setBody(okHttpBody.getParseHttpBody()); } return parseRequestBuilder.build(); }
From source file:com.parse.ParseOkHttpClientTest.java
License:Open Source License
@Test public void testGetOkHttpRequestType() throws IOException { ParseOkHttpClient parseClient = new ParseOkHttpClient(10000, null); ParseHttpRequest.Builder builder = new ParseHttpRequest.Builder(); builder.setUrl("http://www.parse.com"); // Get/* ww w . j av a2 s .c om*/ ParseHttpRequest parseRequest = builder.setMethod(ParseHttpRequest.Method.GET).setBody(null).build(); Request okHttpRequest = parseClient.getRequest(parseRequest); assertEquals(ParseHttpRequest.Method.GET.toString(), okHttpRequest.method()); // Post parseRequest = builder.setMethod(ParseHttpRequest.Method.POST) .setBody(new ParseByteArrayHttpBody("test", "application/json")).build(); okHttpRequest = parseClient.getRequest(parseRequest); assertEquals(ParseHttpRequest.Method.POST.toString(), okHttpRequest.method()); // Delete parseRequest = builder.setMethod(ParseHttpRequest.Method.DELETE).setBody(null).build(); okHttpRequest = parseClient.getRequest(parseRequest); assertEquals(ParseHttpRequest.Method.DELETE.toString(), okHttpRequest.method()); // Put parseRequest = builder.setMethod(ParseHttpRequest.Method.PUT) .setBody(new ParseByteArrayHttpBody("test", "application/json")).build(); okHttpRequest = parseClient.getRequest(parseRequest); assertEquals(ParseHttpRequest.Method.PUT.toString(), okHttpRequest.method()); }