Example usage for com.squareup.okhttp Request urlString

List of usage examples for com.squareup.okhttp Request urlString

Introduction

In this page you can find the example usage for com.squareup.okhttp Request urlString.

Prototype

public String urlString() 

Source Link

Usage

From source file:at.bitfire.dav4android.exception.HttpException.java

License:Open Source License

public HttpException(Response response) {
    super(response.code() + " " + response.message());

    status = response.code();//  ww w .j a va2s.c o m
    message = response.message();

    /* As we don't know the media type and character set of request and response body,
       only printable ASCII characters will be shown in clear text. Other octets will
       be shown as "[xx]" where xx is the hex value of the octet.
     */

    // format request
    Request request = response.request();
    StringBuilder formatted = new StringBuilder();
    formatted.append(request.method() + " " + request.urlString() + "\n");
    Headers headers = request.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (request.body() != null)
        try {
            formatted.append("\n");
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            while (!buffer.exhausted())
                appendByte(formatted, buffer.readByte());
        } catch (IOException e) {
        }
    this.request = formatted.toString();

    // format response
    formatted = new StringBuilder();
    formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n");
    headers = response.headers();
    for (String name : headers.names())
        for (String value : headers.values(name))
            formatted.append(name + ": " + value + "\n");
    if (response.body() != null)
        try {
            formatted.append("\n");
            for (byte b : response.body().bytes())
                appendByte(formatted, b);
        } catch (IOException e) {
        }
    this.response = formatted.toString();
}

From source file:com.auth0.api.internal.ApplicationInfoRequest.java

License:Open Source License

@Override
protected Request doBuildRequest(Request.Builder builder) {
    final Request request = builder.build();
    Log.v(TAG, "Fetching application info from " + request.urlString());
    return request;
}

From source file:com.brq.wallet.external.glidera.api.GlideraService.java

private GlideraService(@NonNull final NetworkParameters networkParameters) {
    Preconditions.checkNotNull(networkParameters);

    this.networkParameters = networkParameters;
    this.baseUrl = getBaseUrl(networkParameters);

    if (networkParameters.isTestnet()) {
        clientId = TESTNET_CLIENT_ID;/*  www  .jav  a  2 s.  c om*/
    } else {
        clientId = MAINNET_CLIENT_ID;
    }

    /**
     * The Sha256 HMAC hash of the message. Use the secret matching the access_key to hash the message.
     * The message is the concatenation of the X-ACCESS-NONCE + URI of the request + message body JSON.
     * The final X-ACCESS-SIGNATURE is the HmacSha256 of the UTF-8 encoding of the message as a Hex encoded string
     */
    final Interceptor apiCredentialInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            if (_oAuth1Response != null) {
                Request.Builder requestBuilder = request.newBuilder();

                synchronized (_nonce) {
                    final String nonce = _nonce.getNonceString();
                    final String uri = request.urlString();

                    String message = nonce + uri;

                    if (request.body() != null && request.body().contentLength() > 0) {
                        Buffer bodyBuffer = new Buffer();
                        request.body().writeTo(bodyBuffer);
                        byte[] bodyBytes = bodyBuffer.readByteArray();

                        String body = new String(bodyBytes, Charsets.UTF_8);
                        message += body;
                    }

                    final byte[] messageBytes = message.getBytes(Charsets.UTF_8);
                    final byte[] secretBytes = _oAuth1Response.getSecret().getBytes(Charsets.UTF_8);
                    final byte[] signatureBytes = Hmac.hmacSha256(secretBytes, messageBytes);

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    Hex.encode(signatureBytes, stream);
                    final String signature = stream.toString();

                    request = requestBuilder.header(HEADER_ACCESS_KEY, _oAuth1Response.getAccess_key())
                            .header(HEADER_ACCESS_NONCE, nonce).header(HEADER_ACCESS_SIGNATURE, signature)
                            .build();

                }
            }

            return chain.proceed(request);
        }
    };

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15000, TimeUnit.MILLISECONDS);
    client.setReadTimeout(15000, TimeUnit.MILLISECONDS);
    client.networkInterceptors().add(apiCredentialInterceptor);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    //objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.);
    objectMapper.registerModule(new WapiJsonModule());

    /*
    We should always add client_id to the header
     */
    RequestInterceptor requestInterceptor = new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade requestFacade) {
            requestFacade.addHeader(HEADER_CLIENT_ID, clientId);
        }
    };

    /*
    Create the json adapter
     */
    RestAdapter adapter = new RestAdapter.Builder().setEndpoint(baseUrl + "/api/" + API_VERSION + "/")
            //.setLogLevel(RestAdapter.LogLevel.FULL)
            .setLogLevel(RestAdapter.LogLevel.BASIC).setLog(new AndroidLog("Glidera"))
            .setConverter(new JacksonConverter(objectMapper)).setClient(new NullBodyAwareOkClient(client))
            .setRequestInterceptor(requestInterceptor).build();

    glideraApi = adapter.create(GlideraApi.class);
}

From source file:com.digi.wva.internal.HttpClient.java

License:Mozilla Public License

/**
 * Log information of OkHttp Request objects
 *
 * <p>This method is protected, rather than private, due to a bug between JaCoCo and
 * the Android build tools which causes the instrumented bytecode to be invalid when this
 * method is private://from  w  ww . ja  va2 s.  c o  m
 * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a>
 * </p>
 */
protected void logRequest(Request request) {
    if (!doLogging) {
        // Logging is disabled - do nothing.
        return;
    }

    Log.i(TAG, "\u2192 " + request.method() + " " + request.urlString());
}

From source file:com.digi.wva.internal.HttpClient.java

License:Mozilla Public License

/**
 * Log information of OkHttp Response objects
 *
 * <p>This method is protected, rather than private, due to a bug between JaCoCo and
 * the Android build tools which causes the instrumented bytecode to be invalid when this
 * method is private://from w w  w .ja v  a2s  . c  om
 * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a>
 * </p>
 * @param response the HTTP response object to log
 */
protected void logResponse(Response response) {
    if (!doLogging) {
        // Logging is disabled - do nothing.
        return;
    }

    Request request = response.request();

    StringBuilder log = new StringBuilder();
    log.append(
            // e.g. <-- 200 GET /ws/hw/leds/foo
            String.format("\u2190 %d %s %s", response.code(), request.method(), request.urlString()));

    // Add on lines tracking any redirects that occurred.
    Response prior = response.priorResponse();
    if (prior != null) {
        // Call out that there were prior responses.
        log.append(" (prior responses below)");

        // Add a line to the log message for each prior response.
        // (For most if not all responses, there will likely be just one.)
        do {
            log.append(String.format("\n... prior response: %d %s %s", prior.code(), prior.request().method(),
                    prior.request().urlString()));

            // If this is a redirect, log the URL we're being redirected to.
            if (prior.isRedirect()) {
                log.append(", redirecting to ");
                log.append(prior.header("Location", "[no Location header found?!]"));
            }

            prior = prior.priorResponse();
        } while (prior != null);
    }

    Log.i(TAG, log.toString());
}

From source file:com.github.kskelm.baringo.ImageService.java

License:Open Source License

/**
 * Given an image id and an output stream, download the image
 * and write it to the stream. It is the caller's responsibility
 * to close everything./* w w  w  .j  a va2s.  c om*/
 * <p>
 * NOTE: This is synchronous.
 * <p>
 * <b>ACCESS: ANONYMOUS</b>
 * @param imageLink the image link to download (could be a thumb too)
 * @param outStream an output stream to write the data to
 * @return the number of bytes written
 * @throws IOException could be anything really
 * @throws BaringoApiException Imgur didn't like something
 */
public long downloadImage(String imageLink, OutputStream outStream) throws IOException, BaringoApiException {

    Request request = new Request.Builder().url(imageLink).build();

    OkHttpClient client = new OkHttpClient();
    com.squareup.okhttp.Response resp = client.newCall(request).execute();

    if (resp.code() != 200 || !resp.isSuccessful()) {
        throw new BaringoApiException(request.urlString() + ": " + resp.message(), resp.code());
    } // if
    if (resp.body() == null) {
        throw new BaringoApiException("No response body found");
    } // if

    InputStream is = resp.body().byteStream();

    BufferedInputStream input = new BufferedInputStream(is);
    byte[] data = new byte[8192]; // because powers of two are magic

    long total = 0;
    int count = 0;
    while ((count = input.read(data)) != -1) {
        total += count;
        outStream.write(data, 0, count);
    } // while

    return total;
}

From source file:com.groupon.mesos.util.HttpProtocolSender.java

License:Apache License

@Override
public void onFailure(final Request request, final IOException e) {
    final Object tag = request.tag();
    checkState(tag != null, "saw a request with null tag");

    final SettableFuture<Void> future = inFlight.remove(tag);
    checkState(future != null, "Saw tag %s but not in in flight map", tag);
    future.setException(e);//www .j  a v a  2s.  c o m

    LOG.warn("While running %s %s: %s", request.method(), request.urlString(), e.getMessage());
}

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  ava 2  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.watson.developer_cloud.concept_insights.v2.ConceptInsights.java

License:Open Source License

/**
 * Execute the request and return the POJO that represent the response.
 * //from ww w  . ja  v  a  2 s  .  c o m
 * @param <T> The POJO that represents the response object
 * @param resourcePath the resource path
 * @param queryParams the query parameters
 * @param returnType the POJO class to be parsed from the response
 * @return the POJO object that represent the response
 */
private <T extends GenericModel> T executeRequest(final String resourcePath,
        final Map<String, Object> queryParams, final Class<T> returnType) {
    final RequestBuilder requestBuilder = RequestBuilder.get(resourcePath);
    if (queryParams != null && !queryParams.isEmpty()) {
        for (final Map.Entry<String, Object> entry : queryParams.entrySet()) {
            requestBuilder.withQuery(entry.getKey(), entry.getValue());
        }
    }
    Request request = requestBuilder.build();
    //    System.out.println("request = " + request);
    //    System.out.println("request = " + request.urlString());
    int length = request.urlString().length();
    // System.out.println(length);
    if (length > 2083)
        System.out.println("Watson-java-sdk|ConceptInsights  WARNING: URL longer than 2083 characters");
    return executeRequest(request, returnType);
}

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

License:Open Source License

/**
 * Test delete./*from   w  w  w .  j  a  v a2 s  .  c  om*/
 */
@Test
public void testDelete() {
    final Request request = RequestBuilder.delete(urlWithQuery).build();
    assertEquals("DELETE", request.method());
    assertEquals(urlWithQuery, request.urlString());
}