List of usage examples for com.squareup.okhttp Request newBuilder
public Builder newBuilder()
From source file:com.ibm.mobilefirstplatform.clientsdk.android.analytics.internal.MetadataHeaderInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Request requestWithHeaders;//ww w.j a v a 2 s .co m if (BMSAnalytics.getAppName() != null) { try { analyticsMetadataHeaderObject.put("mfpAppName", BMSAnalytics.getAppName()); } catch (JSONException e) { //App name not recorded. } } requestWithHeaders = request.newBuilder() .header(ANALYTICS_DEVICE_METADATA_HEADER_NAME, analyticsMetadataHeaderObject.toString()).build(); com.squareup.okhttp.Response response = chain.proceed(requestWithHeaders); return response; }
From source file:com.ibm.mobilefirstplatform.clientsdk.android.analytics.internal.NetworkLoggingInterceptor.java
License:Apache License
@Override public com.squareup.okhttp.Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); long startTime = System.currentTimeMillis(); String trackingID = UUID.randomUUID().toString(); Request requestWithHeaders = request.newBuilder().header("x-wl-analytics-tracking-id", trackingID).build(); com.squareup.okhttp.Response response = chain.proceed(requestWithHeaders); if (BMSAnalytics.isRecordingNetworkEvents) { JSONObject metadata = generateRoundTripRequestAnalyticsMetadata(request, startTime, trackingID, response);/*from w w w . j a v a 2 s. c om*/ if (metadata != null) { BMSAnalytics.log(metadata); } } return response; }
From source file:com.ibm.watson.developer_cloud.service.WatsonService.java
License:Open Source License
/** * Execute the HTTP request.// www .j av a2s .c o m * * @param request the HTTP request * * @return the HTTP response */ protected Response execute(Request request) { final Builder builder = request.newBuilder(); // Set service endpoint for relative paths if (RequestUtil.isRelative(request)) { builder.url(RequestUtil.replaceEndPoint(request.urlString(), getEndPoint())); } // Set default headers if (defaultHeaders != null) { for (String key : defaultHeaders.names()) builder.header(key, defaultHeaders.get(key)); } // Set User-Agent builder.header(HttpHeaders.USER_AGENT, getUserAgent()); // Set Authentication setAuthentication(builder); final Request newRequest = builder.build(); Response response; log.log(Level.FINEST, "Request to: " + newRequest.urlString()); try { response = client.newCall(newRequest).execute(); } catch (final IOException e) { log.log(Level.SEVERE, "IOException", e); throw new RuntimeException(e); } if (response.isSuccessful()) { return response; } final int status = response.code(); // There was a Client Error 4xx or a Server Error 5xx // Get the error message and create the exception final String error = getErrorMessage(response); log.log(Level.SEVERE, newRequest.urlString() + ", status: " + status + ", error: " + error); switch (status) { case HttpStatus.BAD_REQUEST: // HTTP 400 throw new BadRequestException(error != null ? error : "Bad Request", response); case HttpStatus.UNAUTHORIZED: // HTTP 401 throw new UnauthorizedException("Unauthorized: Access is denied due to invalid credentials", response); case HttpStatus.FORBIDDEN: // HTTP 403 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response); case HttpStatus.NOT_FOUND: // HTTP 404 throw new NotFoundException(error != null ? error : "Not found", response); case HttpStatus.NOT_ACCEPTABLE: // HTTP 406 throw new ForbiddenException(error != null ? error : "Forbidden: Service refuse the request", response); case HttpStatus.CONFLICT: // HTTP 409 throw new ConflictException(error != null ? error : "", response); case HttpStatus.REQUEST_TOO_LONG: // HTTP 413 throw new RequestTooLargeException( error != null ? error : "Request too large: The request entity is larger than the server is able to process", response); case HttpStatus.UNSUPPORTED_MEDIA_TYPE: // HTTP 415 throw new UnsupportedException(error != null ? error : "Unsupported Media Type", response); case HttpStatus.TOO_MANY_REQUESTS: // HTTP 429 throw new TooManyRequestsException(error != null ? error : "Too many requests", response); case HttpStatus.INTERNAL_SERVER_ERROR: // HTTP 500 throw new InternalServerErrorException(error != null ? error : "Internal Server Error", response); case HttpStatus.SERVICE_UNAVAILABLE: // HTTP 503 throw new ServiceUnavailableException(error != null ? error : "Service Unavailable", response); default: // other errors throw new ServiceResponseException(status, error, response); } }
From source file:com.karumi.marvelapiclient.AuthInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { String timestamp = String.valueOf(timeProvider.currentTimeMillis()); String hash = null;/*from w w w . j av a 2s . c om*/ try { hash = authHashGenerator.generateHash(timestamp, publicKey, privateKey); } catch (MarvelApiException e) { e.printStackTrace(); } Request request = chain.request(); HttpUrl url = request.httpUrl().newBuilder().addQueryParameter(TIMESTAMP_KEY, timestamp) .addQueryParameter(APIKEY_KEY, publicKey).addQueryParameter(HASH_KEY, hash).build(); request = request.newBuilder().url(url).build(); return chain.proceed(request); }
From source file:com.karumi.todoapiclient.interceptor.DefaultHeadersInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); request = request.newBuilder().addHeader("Accept", "application/json") .addHeader("Content-Type", "application/json").build(); return chain.proceed(request); }
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 {/*w w w.j ava 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.liferay.mobile.screens.context.LiferayServerContext.java
License:Open Source License
public static OkHttpClient getOkHttpClientNoCache() { OkHttpClient noCacheClient = getOkHttpClient().clone(); noCacheClient.interceptors().add(new Interceptor() { @Override/*from ww w .j a v a 2s.c o m*/ public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request newRequest = originalRequest.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build(); return chain.proceed(newRequest); } }); return noCacheClient; }
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. j a v a2 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.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); }/*from w w w.j ava2 s . co 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.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 ww w .j a v a 2 s. c o m*/ 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()); }