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.facebook.react.devsupport.DevServerHelper.java

License:Open Source License

private void enqueueOnChangeEndpointLongPolling() {
    Request request = new Request.Builder().url(createOnChangeEndpointUrl()).tag(this).build();
    Assertions.assertNotNull(mOnChangePollingClient).newCall(request).enqueue(new Callback() {
        @Override//w w  w  .  ja  v  a 2s.  c o  m
        public void onFailure(Request request, IOException e) {
            if (mOnChangePollingEnabled) {
                // this runnable is used by onchange endpoint poller to delay subsequent requests in case
                // of a failure, so that we don't flood network queue with frequent requests in case when
                // dev server is down
                FLog.d(ReactConstants.TAG, "Error while requesting /onchange endpoint", e);
                mRestartOnChangePollingHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        handleOnChangePollingResponse(false);
                    }
                }, LONG_POLL_FAILURE_DELAY_MS);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            handleOnChangePollingResponse(response.code() == 205);
        }
    });
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data,
        final Callback callback) {
    // We need to call the callback to avoid leaking memory on JS even when input for sending
    // request is erroneous or insufficient. For non-http based failures we use code 0, which is
    // interpreted as a transport error.
    // Callback accepts following arguments: responseCode, headersString, responseBody

    Request.Builder requestBuilder = new Request.Builder().url(url);

    if (requestId != 0) {
        requestBuilder.tag(requestId);/*from   w w w .  ja v a2  s  . c o m*/
    }

    Headers requestHeaders = extractHeaders(headers, data);
    if (requestHeaders == null) {
        callback.invoke(0, null, "Unrecognized headers format");
        return;
    }
    String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
    String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
    requestBuilder.headers(requestHeaders);

    if (data == null) {
        requestBuilder.method(method, null);
    } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String body = data.getString(REQUEST_BODY_KEY_STRING);
        MediaType contentMediaType = MediaType.parse(contentType);
        if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
            RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
            if (requestBody == null) {
                callback.invoke(0, null, "Failed to gzip request body");
                return;
            }
            requestBuilder.method(method, requestBody);
        } else {
            requestBuilder.method(method, RequestBody.create(contentMediaType, body));
        }
    } else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String uri = data.getString(REQUEST_BODY_KEY_URI);
        InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
        if (fileInputStream == null) {
            callback.invoke(0, null, "Could not retrieve file for uri " + uri);
            return;
        }
        requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
    } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
        if (contentType == null) {
            contentType = "multipart/form-data";
        }
        ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
        MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
        if (multipartBuilder == null) {
            return;
        }
        requestBuilder.method(method, multipartBuilder.build());
    } else {
        // Nothing in data payload, at least nothing we could understand anyway.
        // Ignore and treat it as if it were null.
        requestBuilder.method(method, null);
    }

    mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (mShuttingDown) {
                return;
            }
            // We need to call the callback to avoid leaking memory on JS even when input for
            // sending request is erronous or insufficient. For non-http based failures we use
            // code 0, which is interpreted as a transport error
            callback.invoke(0, null, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (mShuttingDown) {
                return;
            }
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                // The stream has been cancelled or closed, nothing we can do
                callback.invoke(0, null, e.getMessage());
                return;
            }

            WritableMap responseHeaders = Arguments.createMap();
            Headers headers = response.headers();
            for (int i = 0; i < headers.size(); i++) {
                String headerName = headers.name(i);
                // multiple values for the same header
                if (responseHeaders.hasKey(headerName)) {
                    responseHeaders.putString(headerName,
                            responseHeaders.getString(headerName) + ", " + headers.value(i));
                } else {
                    responseHeaders.putString(headerName, headers.value(i));
                }
            }

            callback.invoke(response.code(), responseHeaders, responseBody);
        }
    });
}

From source file:com.frostwire.util.http.OKHTTPClient.java

License:Open Source License

@Override
public int head(String url, int connectTimeoutInMillis, Map<String, List<String>> outputHeaders)
        throws IOException {
    final OkHttpClient okHttpClient = newOkHttpClient();
    okHttpClient.setConnectTimeout(connectTimeoutInMillis, TimeUnit.MILLISECONDS);
    okHttpClient.setFollowRedirects(false);
    Request req = new Request.Builder().url(url).header("User-Agent", DEFAULT_USER_AGENT).head().build();
    Response resp = okHttpClient.newCall(req).execute();
    copyMultiMap(resp.headers().toMultimap(), outputHeaders);
    return resp.code();
}

From source file:com.frostwire.util.http.OKHTTPClient.java

License:Open Source License

private String getPostSyncResponse(Request.Builder builder) throws IOException {
    String result = null;//www  . j  a v a 2s  .  co m
    final OkHttpClient okHttpClient = newOkHttpClient();
    final Response response = this.getSyncResponse(okHttpClient, builder);
    int httpResponseCode = response.code();

    if ((httpResponseCode != HttpURLConnection.HTTP_OK)
            && (httpResponseCode != HttpURLConnection.HTTP_PARTIAL)) {
        throw new ResponseCodeNotSupportedException(httpResponseCode);
    }

    if (canceled) {
        onCancel();
    } else {
        result = response.body().string();
        onComplete();
    }
    return result;
}

From source file:com.gezhii.fitgroup.network.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();
    int timeoutMs = 30000;
    Log.i("timeoutMs", timeoutMs);
    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  ww  .jav a  2  s  . c  om*/
    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;
}

From source file:com.github.airk.tool.sobitmap.NetworkHunter.java

License:Apache License

@Override
File preCacheFile() {//from   w  w  w .j  a v  a  2s .  com
    File file = null;
    try {
        Request netReq = new Request.Builder().url(request.source.toString()).build();
        Response response = client.newCall(netReq).execute();
        if (response.code() >= 300) {
            if (SoBitmap.LOG) {
                Log.d(SoBitmap.TAG, tag() + ": Network error occurred..." + response.code());
            }
            response.body().close();
            request.e = new HuntException(HuntException.REASON_NETWORK_ERROR);
            request.e.setExtra(response.code() + "");
            return null;
        }
        if (SoBitmap.LOG) {
            Log.d(SoBitmap.TAG, tag() + ": Downloading...");
        }
        String size = response.header("content-length");
        if (size != null && !request.options.onlyLevel && Long.parseLong(size) > request.options.maxInput) {
            request.e = new HuntException(HuntException.REASON_TOO_LARGE);
            return null;
        }
        file = new File(request.cacheDir, request.tag);
        Util.inputStreamToFile(file, response.body().byteStream());
        if (SoBitmap.LOG) {
            Log.d(SoBitmap.TAG, tag() + ": Downloaded to file -> " + file.getAbsolutePath());
        }
        if (!file.exists()) { //UNLIKELY
            request.e = new HuntException(HuntException.REASON_FILE_NOT_FOUND);
            request.e.setExtra("Download success but file not found.");
            return null;
        } else {
            if (!request.options.onlyLevel && file.length() / 1024 > request.options.maxInput) {
                request.e = new HuntException(HuntException.REASON_TOO_LARGE);
                return null;
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
        request.e = new HuntException(HuntException.REASON_NETWORK_ERROR);
    } catch (IOException ignore) {
        request.e = new HuntException(HuntException.REASON_IO_EXCEPTION);
    }
    return file;
}

From source file:com.github.drrb.surefiresplitter.go.GoServer.java

License:Open Source License

private ResponseBody get(String url) throws CommunicationError {
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    if (username != null && password != null) {
        requestBuilder.addHeader("Authorization", Credentials.basic(username, password));
    }/*from   ww  w  . j  a va 2s  .co  m*/
    Response response = execute(requestBuilder.build());
    if (response.isSuccessful()) {
        return response.body();
    } else {
        String errorMessage = String.format("Bad status code when requesting: %s (%d: %s)", url,
                response.code(), response.message());
        try (ResponseBody responseBody = response.body()) {
            errorMessage += ("\n" + responseBody.string());
        } catch (IOException e) {
            errorMessage += ". Tried to read the response body for a helpful message, but couldn't (Error was '"
                    + e.getMessage() + "').";
        }
        throw new CommunicationError(errorMessage);
    }
}

From source file:com.github.drrb.surefiresplitter.go.GoServer.java

License:Open Source License

private Response execute(Request request) throws CommunicationError {
    System.out.println(" -> " + request.url());
    try {//w  ww.  j a v a  2  s.c om
        Response response = httpClient.newCall(request).execute();
        System.out.println(" <- " + response.code() + ": " + response.message() + " ("
                + Bytes.render(response.body().contentLength()) + ")");
        return response;
    } catch (IOException e) {
        throw new CommunicationError("Connection to Go server failed", e);
    }
}

From source file:com.github.leonardoxh.temporeal.model.listeners.PushSender.java

License:Apache License

public static void send(String entity) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(ApplicationConfiguration.PUSH_SERVICE_URL);
    requestBuilder/*from w  ww.j av a 2 s  .c  om*/
            .post(RequestBody.create(MediaType.parse("application/json"), getJsonOfRegistrationsId(entity)));
    requestBuilder.header("Authorization", ApplicationConfiguration.GCM_PROJECT_ID);
    OkHttpClient okHttp = new OkHttpClient();
    try {
        Response response = okHttp.newCall(requestBuilder.build()).execute();
        System.out.println("Response code: " + response.code());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.github.pockethub.android.util.HttpImageGetter.java

License:Apache License

@Override
public Drawable getDrawable(final String source) {
    try {//from w w w  .  j a  v  a  2 s . c o  m
        Drawable repositoryImage = requestRepositoryImage(source);
        if (repositoryImage != null)
            return repositoryImage;
    } catch (Exception e) {
        // Ignore and attempt request over regular HTTP request
    }

    try {
        String logMessage = "Loading image: " + source;
        Log.d(getClass().getSimpleName(), logMessage);
        Bugsnag.leaveBreadcrumb(logMessage);

        Request request = new Request.Builder().get().url(source).build();

        com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute();

        if (!response.isSuccessful())
            throw new IOException("Unexpected response code: " + response.code());

        Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());

        if (bitmap == null)
            return loading.getDrawable(source);

        BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
        drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
        return drawable;
    } catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Error loading image", e);
        Bugsnag.notify(e);
        return loading.getDrawable(source);
    }
}