Example usage for com.squareup.okhttp Response message

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

Introduction

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

Prototype

String message

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

Click Source Link

Usage

From source file:com.twitter.heron.scheduler.kubernetes.KubernetesUtils.java

License:Open Source License

static String errorMessageFromResponse(Response response) {
    final String message = response.message();
    String details;/*  www.  j a  v a 2s  .co  m*/
    try {
        details = response.body().string();
    } catch (IOException ioe) {
        // ignore
        details = ioe.getMessage();
    }
    return message + "\ndetails:\n" + details;
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

License:Apache License

private void checkStatusCode(Response response) throws HttpStatusException, IOException {
    int code = response.code();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;/*from ww  w  .  j  ava  2s. c  o m*/
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
    default:
        String body = "<empty>";
        body = CharStreams.toString(response.body().charStream()).trim();
        String message = String.format("Request not successful. Message: %s. Status-Code: %s. Content: %s.",
                response.message(), response.code(), body);
        throw new HttpStatusException(response.code(), response.message(), message);
    }
}

From source file:com.yandex.disk.rest.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String hash = Integer.toHexString(chain.hashCode());
    String sendPrefix = hash + SEND_PREFIX;
    String receivePrefix = hash + RECEIVE_PREFIX;

    if (logWire) {
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            logger.info(sendPrefix + "request: " + requestBody);
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            byte[] requestBuffer = ByteStreams.toByteArray(buffer.inputStream());
            logBuffer(sendPrefix, requestBuffer);
        }/*ww w.j  av  a2  s.  com*/
        request = request.newBuilder().removeHeader("Accept-Encoding").addHeader("Accept-Encoding", "").build();
    }

    logger.info(sendPrefix + request.method() + " " + request.url());
    logger.info(sendPrefix + "on " + chain.connection());
    logHeaders(sendPrefix, request.headers());

    Response response = chain.proceed(request);
    logger.info(receivePrefix + response.protocol() + " " + response.code() + " " + response.message());
    logHeaders(receivePrefix, response.headers());

    if (logWire) {
        ResponseBody body = response.body();
        byte[] responseBuffer = ByteStreams.toByteArray(body.byteStream());
        response = response.newBuilder().body(ResponseBody.create(body.contentType(), responseBuffer)).build();
        logBuffer(receivePrefix, responseBuffer);
    }

    return response;
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void uploadFile(final String url, final File file, final long startOffset,
        final ProgressListener progressListener) throws IOException, HttpCodeException {
    logger.debug("uploadFile: put to url: " + url);
    MediaType mediaType = MediaType.parse("application/octet-stream");
    RequestBody requestBody = RequestBodyProgress.create(mediaType, file, startOffset, progressListener);
    Request.Builder requestBuilder = buildRequest().removeHeader(Credentials.AUTHORIZATION_HEADER).url(url)
            .put(requestBody);//from   w ww  .  j a  v  a 2s. c  om
    if (startOffset > 0) {
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes ").append(startOffset).append("-").append(file.length() - 1).append("/")
                .append(file.length());
        logger.debug(CONTENT_RANGE_HEADER + ": " + contentRange);
        requestBuilder.addHeader(CONTENT_RANGE_HEADER, contentRange.toString());
    }
    Request request = requestBuilder.build();

    Response response = client.newCall(request).execute();

    String statusLine = response.message();
    logger.debug("headUrl: " + statusLine + " for url " + url);

    int code = response.code();

    ResponseBody responseBody = response.body();
    responseBody.close();

    switch (code) {
    case 201:
    case 202:
        logger.debug("uploadFile: file uploaded successfully: " + file);
        break;
    case 404:
        throw new NotFoundException(code, null);
    case 409:
        throw new ConflictException(code, null);
    case 412:
        throw new PreconditionFailedException(code, null);
    case 413:
        throw new FileTooBigException(code, null);
    case 503:
        throw new ServiceUnavailableException(code, null);
    case 507:
        throw new InsufficientStorageException(code, null);
    default:
        throw new HttpCodeException(code);
    }
}

From source file:com.ydh.gva.util.net.volley.toolbox.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();
    okHttpRequestBuilder.addHeader("clientos", "101");
    okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + "");
    okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + "");
    okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + "");

    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/*from  w  w  w .  j a v a  2s  .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;
}

From source file:de.ebf.GetTranslationsOneSkyAppMojo.java

License:Apache License

private void getTranslations() throws MojoExecutionException {
    try {//from ww  w  .ja  v a2  s  .c  om
        for (String sourceFileName : sourceFileNames) {
            for (String locale : locales) {
                System.out
                        .println(String.format("Downloading %1s translations for %2s", locale, sourceFileName));

                OkHttpClient okHttpClient = new OkHttpClient();
                final String url = String.format(
                        API_ENDPOINT + "projects/%1$s/translations?locale=%2$s&source_file_name=%3$s&%4$s",
                        projectId, locale, sourceFileName, getAuthParams());
                final Request request = new Request.Builder().get().url(url).build();
                final Response response = okHttpClient.newCall(request).execute();

                if (response.code() == 200) {
                    if (!outputDir.exists()) {
                        outputDir.mkdirs();
                    }
                    //even though the OneSkyApp API documentation states that the file name should be sourceFileName_locale.sourceFileNameExtension, it is just locale.sourceFileNameExtension)
                    //https://github.com/onesky/api-documentation-platform/blob/master/resources/translation.md

                    String targetFileName = sourceFileName + "_" + locale;
                    int index = sourceFileName.lastIndexOf(".");
                    if (index > 0) {
                        targetFileName = sourceFileName.substring(0, index) + "_" + locale + "."
                                + sourceFileName.substring(index + 1);
                    }
                    File outputFile = new File(outputDir, targetFileName);
                    outputFile.createNewFile();
                    final InputStream inputStream = response.body().byteStream();
                    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                    IOUtils.copy(inputStream, fileOutputStream);
                    System.out.println(String.format("Successfully downloaded %1s translation for %2s to %3s",
                            locale, sourceFileName, outputFile.getName()));
                } else {
                    throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s",
                            response.code(), response.message()));
                }
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.ebf.UploadFileOneSkyAppMojo.java

License:Apache License

private void uploadFiles() throws MojoExecutionException {
    try {// w w  w .j  a v a2 s .  c  om
        for (File file : files) {
            System.out.println(String.format("Uploading %1$s", file.getName()));
            OkHttpClient okHttpClient = new OkHttpClient();
            final String url = String.format(
                    API_ENDPOINT + "projects/%1$s/files?file_format=%2$s&locale=%3$s&%4$s", projectId,
                    fileFormat, locale, getAuthParams());

            RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                    .addPart(
                            Headers.of("Content-Disposition",
                                    "form-data; name=\"file\"; filename=\"" + file.getName() + "\""),
                            RequestBody.create(MediaType.parse("text/plain"), file))
                    .build();

            final Request request = new Request.Builder().post(requestBody).url(url).build();
            final Response response = okHttpClient.newCall(request).execute();

            if (response.code() == 201) {
                System.out.println(String.format("Successfully uploaded %1$s", file.getName()));
            } else {
                throw new MojoExecutionException(String.format("OneSkyApp API returned %1$s: %2s, %3$s",
                        response.code(), response.message(), response.body().string()));
            }
        }
    } catch (IOException | MojoExecutionException ex) {
        if (failOnError == null || failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            System.out.println("Caught exception: " + ex.getMessage());
        }
    }
}

From source file:de.schildbach.wallet.ui.send.RequestWalletBalanceTask.java

License:Open Source License

public void requestWalletBalance(final Address... addresses) {
    backgroundHandler.post(new Runnable() {
        @Override//from   w w w  . ja v  a 2  s.  c  o  m
        public void run() {
            org.bitcoinj.core.Context.propagate(Constants.CONTEXT);

            final HttpUrl.Builder url = HttpUrl.parse(Constants.BITEASY_API_URL).newBuilder();
            url.addPathSegment("outputs");
            url.addQueryParameter("per_page", "MAX");
            url.addQueryParameter("operator", "AND");
            url.addQueryParameter("spent_state", "UNSPENT");
            for (final Address address : addresses)
                url.addQueryParameter("address[]", address.toBase58());

            log.debug("trying to request wallet balance from {}", url.build());

            final Request.Builder request = new Request.Builder();
            request.url(url.build());
            request.cacheControl(new CacheControl.Builder().noCache().build());
            request.header("Accept-Charset", "utf-8");
            if (userAgent != null)
                request.header("User-Agent", userAgent);

            final Call call = Constants.HTTP_CLIENT.newCall(request.build());
            try {
                final Response response = call.execute();
                if (response.isSuccessful()) {
                    final String content = response.body().string();
                    final JSONObject json = new JSONObject(content);

                    final int status = json.getInt("status");
                    if (status != 200)
                        throw new IOException("api status " + status + " when fetching unspent outputs");

                    final JSONObject jsonData = json.getJSONObject("data");

                    final JSONObject jsonPagination = jsonData.getJSONObject("pagination");

                    if (!"false".equals(jsonPagination.getString("next_page")))
                        throw new IOException("result set too big");

                    final JSONArray jsonOutputs = jsonData.getJSONArray("outputs");

                    final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>(
                            jsonOutputs.length());

                    for (int i = 0; i < jsonOutputs.length(); i++) {
                        final JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                        final Sha256Hash uxtoHash = Sha256Hash.wrap(jsonOutput.getString("transaction_hash"));
                        final int uxtoIndex = jsonOutput.getInt("transaction_index");
                        final byte[] uxtoScriptBytes = Constants.HEX
                                .decode(jsonOutput.getString("script_pub_key"));
                        final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value")));

                        Transaction tx = transactions.get(uxtoHash);
                        if (tx == null) {
                            tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash);
                            tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING);
                            transactions.put(uxtoHash, tx);
                        }

                        final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                uxtoValue, uxtoScriptBytes);

                        if (tx.getOutputs().size() > uxtoIndex) {
                            // Work around not being able to replace outputs on transactions
                            final List<TransactionOutput> outputs = new ArrayList<TransactionOutput>(
                                    tx.getOutputs());
                            final TransactionOutput dummy = outputs.set(uxtoIndex, output);
                            checkState(dummy.getValue().equals(Coin.NEGATIVE_SATOSHI),
                                    "Index %s must be dummy output", uxtoIndex);
                            // Remove and re-add all outputs
                            tx.clearOutputs();
                            for (final TransactionOutput o : outputs)
                                tx.addOutput(o);
                        } else {
                            // Fill with dummies as needed
                            while (tx.getOutputs().size() < uxtoIndex)
                                tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx,
                                        Coin.NEGATIVE_SATOSHI, new byte[] {}));

                            // Add the real output
                            tx.addOutput(output);
                        }
                    }

                    log.info("fetched unspent outputs from {}", url);

                    onResult(transactions.values());
                } else {
                    final int responseCode = response.code();
                    final String responseMessage = response.message();

                    log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url);
                    onFail(R.string.error_http, responseCode, responseMessage);
                }
            } catch (final JSONException x) {
                log.info("problem parsing json from " + url, x);

                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs from " + url, x);

                onFail(R.string.error_io, x.getMessage());
            }
        }
    });
}

From source file:feign.okhttp.OkHttpClient.java

License:Apache License

private static feign.Response toFeignResponse(Response input) {
    return feign.Response.create(input.code(), input.message(), toMap(input.headers()), toBody(input.body()));
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * @param response/*from   w w w.j  a  va  2  s.  c  o  m*/
 */
private static HawkularMetricsException hawkularMetricsError(Response response) {
    // TODO better error handling goes here.
    return new UnexpectedMetricsException(response.message());
}