Example usage for com.squareup.okhttp Response code

List of usage examples for com.squareup.okhttp Response code

Introduction

In this page you can find the example usage for com.squareup.okhttp Response code.

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

/**
 * Get continue search items/*from www.  j a va  2  s .  c  o m*/
 *
 * @param url for the next page of items
 * @param folder where the search is looking at
 * @return List that contains CFile and CFolder
 * @throws RequestFailException that content various error types
 */
public synchronized List<Object> searchContinue(String url, CFolder folder) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }

    List<Object> list = new ArrayList<>();

    Request request = new Request.Builder().url(url)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = new JSONObject(response.body().string());
            JSONArray entries = jsonObject.getJSONArray("data");
            if (entries.length() > 0) {
                list.addAll(createFilteredItemsList(entries, folder));
            } else {
                // return null if no item found
                return null;
            }
            // pagination available
            if (jsonObject.has("@odata.nextLink")) {
                list.addAll(searchContinue(jsonObject.getString("@odata.nextLink"), folder));
            }
            return list;
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

@Override
public File getThumbnail(@NonNull CFile file) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//from   w ww.  ja  v a2s  . com

    Request request = new Request.Builder()
            .url(API_BASE_URL + "/drive/items/" + file.getId() + "/thumbnails/0/medium/content")
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            switch (response.code()) {
            case 200:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".jpg");
            case 302:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".jpg");
            }
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
    return null;
}

From source file:com.heroiclabs.sdk.android.util.http.RetryInterceptor.java

License:Apache License

/**
 * Recursive helper method that catches IOExceptions and calls itself again if the maximum number of allowed
 * retries has not yet been exceeded.// www .  ja v a  2s  . c o  m
 *
 * @param chain The request chain.
 * @param count The number of the current attempt.
 * @return The response forwarded by the chain.
 * @throws IOException if even after all retries the request fails.
 */
private Response attemptRequest(final Chain chain, final int count) throws IOException {
    try {
        final Request request = chain.request();
        final Response response = chain.proceed(request);

        // Treat blank 504 responses as network issues.
        if (response.code() == HttpURLConnection.HTTP_GATEWAY_TIMEOUT
                && response.body().contentLength() == 0l) {
            throw new IOException("Unexpected 504 responses status");
        }

        return response;
    } catch (final IOException e) {
        if (count < maxAttempts) {
            try {
                // Wait between 100 and 200 milliseconds, inclusive.
                Thread.sleep(random.nextInt(101) + 100);
            } catch (final InterruptedException ex) {
                // Don't care.
            }

            return attemptRequest(chain, count + 1);
        } else {
            throw e;
        }
    }
}

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 av 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.hippo.nimingban.client.ConvertEngine.java

License:Apache License

public static String doConvert(Call call) throws Exception {
    try {/*  w  w  w  . j  av a  2  s.c om*/
        Response response = call.execute();
        int code = response.code();
        if (code != 200) {
            throw new ResponseCodeException(code);
        }
        return response.body().string();
    } catch (IOException e) {
        if (call.isCanceled()) {
            throw new CancelledException();
        } else {
            throw e;
        }
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.analytics.internal.NetworkLoggingInterceptor.java

License:Apache License

protected JSONObject generateRoundTripRequestAnalyticsMetadata(Request request, long startTime,
        String trackingID, Response response) throws IOException {
    JSONObject metadata = new JSONObject();

    long endTime = System.currentTimeMillis();

    try {/*from  w  w  w  .  j  a  va2  s .co  m*/
        metadata.put("$path", request.urlString());
        metadata.put(BMSAnalytics.CATEGORY, "network");
        metadata.put("$trackingid", trackingID);
        metadata.put("$outboundTimestamp", startTime);
        metadata.put("$inboundTimestamp", endTime);
        metadata.put("$roundTripTime", endTime - startTime);

        if (response != null) {
            metadata.put("$responseCode", response.code());
        }

        if (response != null && response.body() != null && response.body().contentLength() >= 0) {
            metadata.put("$bytesReceived", response.body().contentLength());
        }

        return metadata;
    } catch (JSONException e) {
        //Do nothing, since it is just for analytics.
        return null;
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request.java

License:Apache License

@Override
protected Callback getCallback(final ResponseListener listener) {
    final RequestBody requestBody = savedRequestBody;
    final Request request = this;
    final Context ctx = this.context;

    return new Callback() {
        @Override/*  ww  w.j  ava  2  s  .  c  o  m*/
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {
            if (listener != null) {
                listener.onFailure(null, e, null);
            }
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            if (listener == null) {
                return;
            }

            AuthorizationManager authorizationManager = BMSClient.getInstance().getAuthorizationManager();
            int responseCode = response.code();
            Map<String, List<String>> responseHeaders = response.headers().toMultimap();
            boolean isAuthorizationRequired = authorizationManager.isAuthorizationRequired(responseCode,
                    responseHeaders);

            if (isAuthorizationRequired) {
                if (oauthFailCounter++ < 2) {
                    authorizationManager.obtainAuthorization(ctx, new ResponseListener() {
                        @Override
                        public void onSuccess(Response response) {
                            // this will take the auth hader that has been cached by obtainAuthorizationHeader
                            request.sendRequest(listener, requestBody);
                        }

                        @Override
                        public void onFailure(Response response, Throwable t, JSONObject extendedInfo) {
                            listener.onFailure(response, t, extendedInfo);
                        }
                    });
                } else {
                    listener.onFailure(new ResponseImpl(response), null, null);
                }
            } else {
                if (response.isSuccessful() || response.isRedirect()) {
                    listener.onSuccess(new ResponseImpl(response));
                } else {
                    listener.onFailure(new ResponseImpl(response), null, null);
                }
            }
        }
    };
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.AuthorizationHeaderHelper.java

License:Apache License

/**
 * A response is an OAuth error response only if,
 * 1. it's status is 401 or 403/*from   w  w w . jav a  2  s  .  c  o m*/
 * 2. The value of the "WWW-Authenticate" header contains 'Bearer'
 *
 * @param response to check the conditions for.
 * @return true if the response satisfies both conditions
 */
public static boolean isAuthorizationRequired(Response response) {
    return isAuthorizationRequired(response.code(), response.headers(WWW_AUTHENTICATE_HEADER));
}

From source file:com.ibm.watson.developer_cloud.service.WatsonService.java

License:Open Source License

/**
 * Execute the HTTP request./*from  ww w  .j  a v a 2  s .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.ichg.service.volley.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from  w  w w  .  j av a 2 s  . co  m
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}