List of usage examples for com.squareup.okhttp Response header
public String header(String name)
From source file:com.gzsll.downloads.DownloadThread.java
License:Apache License
/** * Handle a 3xx redirect status.// w w w .j a v a 2 s. c o m */ private void handleRedirect(State state, Response response, int statusCode) throws StopRequest, RetryDownload { if (Constants.LOGVV) { Log.v(Constants.TAG, "got HTTP redirect " + statusCode); } if (state.mRedirectCount >= Constants.MAX_REDIRECTS) { throw new StopRequest(Downloads.STATUS_TOO_MANY_REDIRECTS, "too many redirects"); } String header = response.header("Location"); if (header == null) { return; } if (Constants.LOGVV) { Log.v(Constants.TAG, "Location :" + header); } String newUri; try { newUri = new URI(mInfo.mUri).resolve(new URI(header)).toString(); } catch (URISyntaxException ex) { if (Constants.LOGV) { Log.d(Constants.TAG, "Couldn't resolve redirect URI " + header + " for " + mInfo.mUri); } throw new StopRequest(Downloads.STATUS_HTTP_DATA_ERROR, "Couldn't resolve redirect URI"); } ++state.mRedirectCount; state.mRequestUri = newUri; if (statusCode == 301 || statusCode == 303) { // use the new URI for all future requests (should a retry/resume be // necessary) state.mNewUri = newUri; } throw new RetryDownload(); }
From source file:com.gzsll.downloads.DownloadThread.java
License:Apache License
/** * Handle a 503 Service Unavailable status by processing the Retry-After * header./*from w w w. j a v a 2 s .c o m*/ */ private void handleServiceUnavailable(State state, Response response) throws StopRequest { if (Constants.LOGVV) { Log.v(Constants.TAG, "got HTTP response code 503"); } state.mCountRetry = true; String header = response.header("Retry-After"); if (header != null) { try { if (Constants.LOGVV) { Log.v(Constants.TAG, "Retry-After :" + header); } state.mRetryAfter = Integer.parseInt(header); if (state.mRetryAfter < 0) { state.mRetryAfter = 0; } else { if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) { state.mRetryAfter = Constants.MIN_RETRY_AFTER; } else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) { state.mRetryAfter = Constants.MAX_RETRY_AFTER; } state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1); state.mRetryAfter *= 1000; } } catch (NumberFormatException ex) { // ignored - retryAfter stays 0 in this case. } } throw new StopRequest(Downloads.STATUS_WAITING_TO_RETRY, "got 503 Service Unavailable, will retry later"); }
From source file:com.hippo.network.DownloadClient.java
License:Apache License
public static boolean execute(DownloadRequest request) { OnDownloadListener listener = request.mListener; OkHttpClient okHttpClient = request.mOkHttpClient; UniFile uniFile = null;// ww w . j a v a 2 s .c o m OutputStreamPipe osPipe = null; try { Call call = okHttpClient.newCall(new GoodRequestBuilder(request.mUrl).build()); request.mCall = call; // Listener if (listener != null) { listener.onStartDownloading(); } Response response = call.execute(); ResponseBody body = response.body(); // Check response code int responseCode = response.code(); if (responseCode >= 400) { throw new ResponseCodeException(responseCode); } osPipe = request.mOSPipe; if (osPipe == null) { String extension; String name; String dispositionFilename = getFilenameFromContentDisposition( response.header("Content-Disposition")); if (dispositionFilename != null) { name = FileUtils.getNameFromFilename(dispositionFilename); extension = FileUtils.getExtensionFromFilename(dispositionFilename); } else { name = Utilities.getNameFromUrl(request.mUrl); extension = Utilities.getExtensionFromMimeType(response.header("Content-Type")); if (extension == null) { extension = MimeTypeMap.getFileExtensionFromUrl(request.mUrl); } } String filename; if (listener != null) { filename = listener.onFixname(name, extension, request.mFilename); } else { filename = request.mFilename; } request.mFilename = filename; // Use Temp filename uniFile = request.mDir.createFile(FileUtils.ensureFilename(filename + ".download")); if (uniFile == null) { // Listener if (listener != null) { listener.onFailed(new IOException("Can't create file " + filename)); } return false; } osPipe = new UniFileOutputStreamPipe(uniFile); } osPipe.obtain(); long contentLength = body.contentLength(); // Listener if (listener != null) { listener.onConnect(contentLength); } long receivedSize = transferData(body.byteStream(), osPipe.open(), listener); if (contentLength > 0 && contentLength != receivedSize) { throw new IOException( "contentLength is " + contentLength + ", but receivedSize is " + receivedSize); } // Rename if (uniFile != null && request.mFilename != null) { uniFile.renameTo(request.mFilename); } // Listener if (listener != null) { listener.onSucceed(); } return true; } catch (Exception e) { // remove download failed file if (uniFile != null) { uniFile.delete(); } if (listener != null) { listener.onFailed(e); } return false; } finally { if (osPipe != null) { osPipe.close(); osPipe.release(); } } }
From source file:com.ibm.watson.developer_cloud.service.AlchemyService.java
License:Open Source License
/** * Gets the error message from the {@link Response} by looking at the headers returned by the * Alchemy service <code>X-AlchemyAPI-Status</code> and <code>X-AlchemyAPI-Error-Msg</code> * //www. jav a 2s . c o m * <pre> * { * code: 400 * error: 'bad request' * } * </pre> * * . * * @param response the HTTP response * @return the error message from the json object */ private JsonObject getErrorMessage(Response response) { final String status = response.header(X_ALCHEMY_API_STATUS); final String errorMessage = response.header(X_ALCHEMY_API_ERROR_MSG); if (status != null && status.equals(STATUS_ERROR)) { final int code = detectErrorCode(errorMessage); final JsonObject error = new JsonObject(); error.addProperty(MESSAGE_ERROR, errorMessage != null ? errorMessage : "Unknown error"); error.addProperty(MESSAGE_CODE, code); return error; } return null; // no error }
From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java
License:Open Source License
private void sendRequest(BaseRequest request, @Nonnull Request.Builder builder, String requestBody, String method) {/*from ww w. j ava 2 s.c om*/ String uri = null; long waitTime = 0L; try { setHeaders(request, builder, request.getHeaderInformation()); List<String> cookies = new ArrayList<String>(); if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) { for (HttpCookie httpCookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore() .getCookies()) { cookies.add("REQUEST COOKIE: " + httpCookie.toString()); } } Request okRequest = builder.build(); uri = okRequest.uri().toString(); LOG.debug(request.getLogUtil().getLogMessage( "About to " + okRequest.method() + " request to " + uri + " with requestBody " + requestBody, LogEventType.Informational)); request.logRequest(uri, requestBody, okRequest.method(), request.getHeaderInformation(), cookies, false); Response response = okHttpClient.newCall(okRequest).execute(); long startTime = Long.parseLong(response.header("OkHttp-Sent-Millis")); long endTime = Long.parseLong(response.header("OkHttp-Sent-Millis")); // read response body byte[] responseBody = new byte[0]; // check for no content headers if (response.code() != 203 && response.code() != 202 && response.code() != 204) { try { responseBody = response.body().bytes(); } catch (Exception e) { LOG.warn("could not get response body: " + e); } } processResponse(responseBody, startTime, endTime, request, response.message(), response.code(), response.headers()); waitTime = endTime - startTime; } catch (Exception ex) { LOG.error(request.getLogUtil().getLogMessage( "Could not do " + method + " to url " + uri + " | error: " + ex.toString(), LogEventType.IO), ex); throw new RuntimeException(ex); } finally { if (method.equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) { LOG.info(request.getLogUtil() .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code " + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody() + " }", LogEventType.Informational)); } } if (waitTime != 0) { doWaitDueToLongResponse(request, waitTime, uri); } }
From source file:com.jaspersoft.android.jaspermobile.webview.intercept.okhttp.OkResponseMapper.java
License:Open Source License
public WebResponse toWebViewResponse(Response response) { final String mimeType = response.header(CONTENT_TYPE); final String encoding = response.header(CONTENT_ENCODING); final InputStream data = extractData(response); final int statusCode = response.code(); final String reasonPhrase = response.message(); final Map<String, String> responseHeaders = extractHeaders(response); return new WebResponse() { @Override/*w w w .j a v a 2 s . c o m*/ public String getMimeType() { return mimeType; } @Override public String getEncoding() { return encoding; } @Override public InputStream getData() { return data; } @Override public int getStatusCode() { return statusCode; } @Override public String getReasonPhrase() { return reasonPhrase; } @Override public Map<String, String> getResponseHeaders() { return responseHeaders; } }; }
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 ww . j a v a 2s . 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 . j a v a2s. 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.liulishuo.filedownloader.services.FileDownloadRunnable.java
License:Apache License
private void updateHeader(Response response) { if (response == null) { throw new RuntimeException("response is null when updateHeader"); }//from www . j a va 2s.c o m boolean needRefresh = false; final String oldEtag = this.etag; final String newEtag = response.header("Etag"); FileDownloadLog.w(this, "etag find by header %s", newEtag); if (oldEtag == null && newEtag != null) { needRefresh = true; } else if (oldEtag != null && newEtag != null && !oldEtag.equals(newEtag)) { needRefresh = true; } if (needRefresh) { this.etag = newEtag; helper.updateHeader(downloadTransfer.getDownloadId(), newEtag); } }
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); }// ww w .j av 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; }