Example usage for com.squareup.okhttp Request httpUrl

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

Introduction

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

Prototype

public HttpUrl httpUrl() 

Source Link

Usage

From source file:com.karumi.marvelapiclient.AuthInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    String timestamp = String.valueOf(timeProvider.currentTimeMillis());
    String hash = null;//from   www .j a v  a 2 s .c o  m
    try {
        hash = authHashGenerator.generateHash(timestamp, publicKey, privateKey);
    } catch (MarvelApiException e) {
        e.printStackTrace();
    }
    Request request = chain.request();
    HttpUrl url = request.httpUrl().newBuilder().addQueryParameter(TIMESTAMP_KEY, timestamp)
            .addQueryParameter(APIKEY_KEY, publicKey).addQueryParameter(HASH_KEY, hash).build();
    request = request.newBuilder().url(url).build();
    return chain.proceed(request);
}

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);
    }/*from ww w .j ava2  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;
}

From source file:com.mamaspapas.api.helper.Oauth1SigningInterceptor.java

License:Apache License

public Request signRequest(Request request) throws IOException {
    byte[] nonce = new byte[32];
    random.nextBytes(nonce);//from   w  w  w. java 2s. co m
    String oauthNonce = ByteString.of(nonce).base64().replaceAll("\\W", "");
    String oauthTimestamp = String.valueOf(clock.millis());

    String consumerKeyValue = ESCAPER.escape(consumerKey);
    String accessTokenValue = ESCAPER.escape(accessToken);

    SortedMap<String, String> parameters = new TreeMap<>();
    parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue);
    parameters.put(OAUTH_ACCESS_TOKEN, accessTokenValue);
    parameters.put(OAUTH_NONCE, oauthNonce);
    parameters.put(OAUTH_TIMESTAMP, oauthTimestamp);
    parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE);
    parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE);

    HttpUrl url = request.httpUrl();
    for (int i = 0; i < url.querySize(); i++) {
        parameters.put(ESCAPER.escape(url.queryParameterName(i)), ESCAPER.escape(url.queryParameterValue(i)));
    }

    //        RequestBody requestBody = request.body();
    //        Buffer body = new Buffer();
    //        requestBody.writeTo(body);

    //        while (!body.exhausted()) {
    //            long keyEnd = body.indexOf((byte) '=');
    //            if (keyEnd == -1) throw new IllegalStateException("Key with no value: " + body.readUtf8());
    //            String key = body.readUtf8(keyEnd);
    //            body.skip(1); // Equals.
    //
    //            long valueEnd = body.indexOf((byte) '&');
    //            String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd);
    //            if (valueEnd != -1) body.skip(1); // Ampersand.
    //
    //            parameters.put(key, value);
    //        }

    Buffer base = new Buffer();
    String method = request.method();
    base.writeUtf8(method);
    base.writeByte('&');
    base.writeUtf8(ESCAPER.escape(request.httpUrl().newBuilder().query(null).build().toString()));
    base.writeByte('&');

    boolean first = true;
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        if (!first)
            base.writeUtf8(ESCAPER.escape("&"));
        first = false;
        base.writeUtf8(ESCAPER.escape(entry.getKey()));
        base.writeUtf8(ESCAPER.escape("="));
        base.writeUtf8(ESCAPER.escape(entry.getValue()));
    }

    String signingKey = ESCAPER.escape(consumerSecret) + "&" + ESCAPER.escape(accessSecret);

    SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new IllegalStateException(e);
    }
    byte[] result = mac.doFinal(base.readByteArray());
    String signature = ByteString.of(result).base64();

    String authorization = "OAuth " + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " + OAUTH_NONCE
            + "=\"" + oauthNonce + "\", " + OAUTH_SIGNATURE + "=\"" + ESCAPER.escape(signature) + "\", "
            + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " + OAUTH_TIMESTAMP + "=\""
            + oauthTimestamp + "\", " + OAUTH_ACCESS_TOKEN + "=\"" + accessTokenValue + "\", " + OAUTH_VERSION
            + "=\"" + OAUTH_VERSION_VALUE + "\"";

    return request.newBuilder().addHeader("Authorization", authorization).build();
}

From source file:com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineConnectMethodFromUserRequestInterceptor.java

License:Apache License

@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result,
        Throwable throwable) {/*from  ww  w  . j  ava 2s . c o  m*/
    recorder.recordApi(methodDescriptor);
    recorder.recordServiceType(OkHttpConstants.OK_HTTP_CLIENT_INTERNAL);
    recorder.recordException(throwable);

    if (target instanceof UserRequestGetter) {
        final Request request = ((UserRequestGetter) target)._$PINPOINT$_getUserRequest();
        if (request != null && request.httpUrl() != null) {
            final HttpUrl httpUrl = request.httpUrl();
            final String hostAndPort = HostAndPort.toHostAndPortString(httpUrl.host(), httpUrl.port());
            recorder.recordAttribute(AnnotationKey.HTTP_INTERNAL_DISPLAY, hostAndPort);
        }
    }
}

From source file:com.rafagarcia.countries.backend.webapi.HttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }// www  . j  a v  a  2 s.  c  o m

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' '
            + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody && hasRequestBody) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                contentType.charset(UTF8);
            }

            logger.log("");
            logger.log(buffer.readString(charset));
        }

        String endMessage = "--> END " + request.method();
        if (logBody && hasRequestBody) {
            endMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    logger.log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody) {
            Buffer buffer = new Buffer();
            responseBody.source().readAll(buffer);

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (responseBody.contentLength() > 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            // Since we consumed the original, replace the one-shot body in the response with a new one.
            response = response.newBuilder()
                    .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build();
        }

        String endMessage = "<-- END HTTP";
        if (logBody) {
            endMessage += " (" + responseBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:com.sam_chordas.android.stockhawk.app.retofit.RestClientPublic.java

License:Apache License

private OkHttpClient getClient() {
    OkHttpClient client = new OkHttpClient();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);

    client.networkInterceptors().add(new Interceptor() {
        @Override//from   ww w . j  av  a2 s  .co  m
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl url = request.httpUrl().newBuilder()
                    .addQueryParameter(App.getGlobalContext().getString(R.string.url_query_format),
                            App.getGlobalContext().getString(R.string.url_query_json))
                    .addQueryParameter(App.getGlobalContext().getString(R.string.url_query_diagnostics),
                            App.getGlobalContext().getString(R.string.url_query_diagnostics_value))
                    .addQueryParameter(App.getGlobalContext().getString(R.string.url_query_evn),
                            App.getGlobalContext().getString(R.string.url_query_evn_value))
                    .build();
            request = request.newBuilder().url(url).build();
            return chain.proceed(request);

        }
    });
    return client;
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAttachesFormFields() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", true).responseAs(Object.class).formField("f",
            "true");
    // Build the CallSpec so that we don't test this behaviour twice.
    builder.build().formField("e", "false");

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();/*from  ww  w.  jav a  2  s  . com*/
    assertThat(body.contentType()).isEqualTo(MediaType.parse("application/x-www-form-urlencoded"));

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("f=true&e=false");
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderAttachesFormFieldsAsLists() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", true).responseAs(Object.class).formField("f",
            "test1", "test2");
    // Build the CallSpec so that we don't test this behaviour twice.
    List<String> field = new ArrayList<>(2);
    field.add("test3");
    field.add("test4");
    builder.build().formField("e", field).formField("d", "test5", "test6");

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();/*from   w ww  .j  a v a  2  s.  co m*/
    assertThat(body.contentType()).isEqualTo(MediaType.parse("application/x-www-form-urlencoded"));

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEqualTo("f=test1%2C%20test2&e=test3%2C%20test4&d=test5%2C%20test6");
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void builderEnsuresEmptyBody() throws Exception {
    CallSpec.Builder builder = builder(HttpMethod.PUT, "", false).responseAs(Object.class);
    // Build the CallSpec so that we can build the request.
    builder.build();//from w ww .  j a  v a  2s.  com

    Request request = builder.request();
    assertThat(request.method()).isEqualTo(HttpMethod.PUT.method());
    assertThat(request.httpUrl()).isEqualTo(httpUrl);
    assertThat(request.body()).isNotNull();

    RequestBody body = request.body();
    assertThat(body.contentType()).isNull();
    assertThat(body.contentLength()).isEqualTo(0);

    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    assertThat(buffer.readUtf8()).isEmpty();
}

From source file:com.xing.api.Oauth1SigningInterceptor.java

License:Apache License

public Request signRequest(Request request) throws IOException {
    byte[] nonce = new byte[NUANCE_BYTES];
    random.nextBytes(nonce);//  w ww . j  a  v a2 s.  co m
    String oauthNonce = CHARACTER_PATTERN.matcher(ByteString.of(nonce).base64()).replaceAll("");
    String oauthTimestamp = clock.millis();

    String consumerKeyValue = UrlEscapeUtils.escape(consumerKey);
    String accessTokenValue = UrlEscapeUtils.escape(accessToken);

    SortedMap<String, String> parameters = new TreeMap<>();
    parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue);
    parameters.put(OAUTH_ACCESS_TOKEN, accessTokenValue);
    parameters.put(OAUTH_NONCE, oauthNonce);
    parameters.put(OAUTH_TIMESTAMP, oauthTimestamp);
    parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE);
    parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE);

    HttpUrl url = request.httpUrl();
    for (int i = 0; i < url.querySize(); i++) {
        parameters.put(UrlEscapeUtils.escape(url.queryParameterName(i)),
                UrlEscapeUtils.escape(url.queryParameterValue(i)));
    }

    Buffer body = new Buffer();
    RequestBody requestBody = request.body();
    if (requestBody != null) {
        requestBody.writeTo(body);
    }

    while (!body.exhausted()) {
        long keyEnd = body.indexOf((byte) '=');
        if (keyEnd == -1) {
            throw new IllegalStateException("Key with no value: " + body.readUtf8());
        }
        String key = body.readUtf8(keyEnd);
        body.skip(1); // Equals.

        long valueEnd = body.indexOf((byte) '&');
        String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd);
        if (valueEnd != -1) {
            body.skip(1); // Ampersand.
        }

        parameters.put(key, value);
    }

    Buffer base = new Buffer();
    String method = request.method();
    base.writeUtf8(method);
    base.writeByte('&');
    base.writeUtf8(UrlEscapeUtils.escape(request.httpUrl().newBuilder().query(null).build().toString()));
    base.writeByte('&');

    boolean first = true;
    for (Entry<String, String> entry : parameters.entrySet()) {
        if (!first) {
            base.writeUtf8(UrlEscapeUtils.escape("&"));
        }
        first = false;
        base.writeUtf8(UrlEscapeUtils.escape(entry.getKey()));
        base.writeUtf8(UrlEscapeUtils.escape("="));
        base.writeUtf8(UrlEscapeUtils.escape(entry.getValue()));
    }

    String signingKey = UrlEscapeUtils.escape(consumerSecret) + '&' + UrlEscapeUtils.escape(accessSecret);
    SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new IllegalStateException(e);
    }
    byte[] result = mac.doFinal(base.readByteArray());
    String signature = ByteString.of(result).base64();

    String authorization = "OAuth " //
            + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " //
            + OAUTH_NONCE + "=\"" + oauthNonce + "\", " //
            + OAUTH_SIGNATURE + "=\"" + UrlEscapeUtils.escape(signature) + "\", " //
            + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " //
            + OAUTH_TIMESTAMP + "=\"" + oauthTimestamp + "\", " //
            + OAUTH_ACCESS_TOKEN + "=\"" + accessTokenValue + "\", " //
            + OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + '"';

    return request.newBuilder().addHeader("Authorization", authorization).build();
}