Search in sources :

Example 96 with Builder

use of okhttp3.Request.Builder in project mbed-cloud-sdk-java by ARMmbed.

the class OAuth method retryingIntercept.

private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
    Request request = chain.request();
    // If the request already have an authorization (eg. Basic auth), do nothing
    if (request.header("Authorization") != null) {
        return chain.proceed(request);
    }
    // If first time, get the token
    OAuthClientRequest oAuthRequest;
    if (getAccessToken() == null) {
        updateAccessToken(null);
    }
    if (getAccessToken() != null) {
        // Build the request
        Builder rb = request.newBuilder();
        String requestAccessToken = new String(getAccessToken());
        try {
            oAuthRequest = new OAuthBearerClientRequest(request.url().toString()).setAccessToken(requestAccessToken).buildHeaderMessage();
        } catch (OAuthSystemException e) {
            throw new IOException(e);
        }
        for (Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet()) {
            rb.addHeader(header.getKey(), header.getValue());
        }
        rb.url(oAuthRequest.getLocationUri());
        // Execute the request
        Response response = chain.proceed(rb.build());
        // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row.
        if (response != null && (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
            if (updateAccessToken(requestAccessToken)) {
                return retryingIntercept(chain, false);
            }
        }
        return response;
    } else {
        return chain.proceed(chain.request());
    }
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) AuthenticationRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder) Builder(okhttp3.Request.Builder) TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) IOException(java.io.IOException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) Map(java.util.Map)

Example 97 with Builder

use of okhttp3.Request.Builder in project mbed-cloud-sdk-java by ARMmbed.

the class OAuth method retryingIntercept.

private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
    Request request = chain.request();
    // If the request already have an authorization (eg. Basic auth), do nothing
    if (request.header("Authorization") != null) {
        return chain.proceed(request);
    }
    // If first time, get the token
    OAuthClientRequest oAuthRequest;
    if (getAccessToken() == null) {
        updateAccessToken(null);
    }
    if (getAccessToken() != null) {
        // Build the request
        Builder rb = request.newBuilder();
        String requestAccessToken = new String(getAccessToken());
        try {
            oAuthRequest = new OAuthBearerClientRequest(request.url().toString()).setAccessToken(requestAccessToken).buildHeaderMessage();
        } catch (OAuthSystemException e) {
            throw new IOException(e);
        }
        for (Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet()) {
            rb.addHeader(header.getKey(), header.getValue());
        }
        rb.url(oAuthRequest.getLocationUri());
        // Execute the request
        Response response = chain.proceed(rb.build());
        // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row.
        if (response != null && (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
            if (updateAccessToken(requestAccessToken)) {
                return retryingIntercept(chain, false);
            }
        }
        return response;
    } else {
        return chain.proceed(chain.request());
    }
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) AuthenticationRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder) Builder(okhttp3.Request.Builder) TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) IOException(java.io.IOException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) Map(java.util.Map)

Example 98 with Builder

use of okhttp3.Request.Builder in project spring-cloud-netflix by spring-cloud.

the class OkHttpRibbonRequestTests method testEntity.

void testEntity(String entityValue, ByteArrayInputStream requestEntity, boolean addContentLengthHeader, String method) throws IOException {
    String lengthString = String.valueOf(entityValue.length());
    Long length = null;
    String uri = "http://example.com";
    LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    if (addContentLengthHeader) {
        headers.add("Content-Length", lengthString);
        length = (long) entityValue.length();
    }
    RibbonRequestCustomizer requestCustomizer = new RibbonRequestCustomizer<Request.Builder>() {

        @Override
        public boolean accepts(Class builderClass) {
            return builderClass == Request.Builder.class;
        }

        @Override
        public void customize(Request.Builder builder) {
            builder.addHeader("from-customizer", "foo");
        }
    };
    RibbonCommandContext context = new RibbonCommandContext("example", method, uri, false, headers, new LinkedMultiValueMap<String, String>(), requestEntity, Collections.singletonList(requestCustomizer));
    context.setContentLength(length);
    OkHttpRibbonRequest httpRequest = new OkHttpRibbonRequest(context);
    Request request = httpRequest.toRequest();
    assertThat("uri is wrong", request.url().toString(), startsWith(uri));
    if (addContentLengthHeader) {
        assertThat("Content-Length is wrong", request.header("Content-Length"), is(equalTo(lengthString)));
    }
    assertThat("from-customizer is wrong", request.header("from-customizer"), is(equalTo("foo")));
    if (!method.equalsIgnoreCase("get")) {
        assertThat("body is null", request.body(), is(notNullValue()));
        RequestBody body = request.body();
        assertThat("contentLength is wrong", body.contentLength(), is(equalTo((long) entityValue.length())));
        Buffer content = new Buffer();
        body.writeTo(content);
        String string = content.readByteString().utf8();
        assertThat("content is wrong", string, is(equalTo(entityValue)));
    }
}
Also used : Buffer(okio.Buffer) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RibbonCommandContext(org.springframework.cloud.netflix.ribbon.support.RibbonCommandContext) RibbonRequestCustomizer(org.springframework.cloud.netflix.ribbon.support.RibbonRequestCustomizer) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 99 with Builder

use of okhttp3.Request.Builder in project spring-cloud-netflix by spring-cloud.

the class OkHttpLoadBalancingClient method getOkHttpClient.

OkHttpClient getOkHttpClient(IClientConfig configOverride, boolean secure) {
    IClientConfig config = configOverride != null ? configOverride : this.config;
    RibbonProperties ribbon = RibbonProperties.from(config);
    OkHttpClient.Builder builder = this.delegate.newBuilder().connectTimeout(ribbon.connectTimeout(this.connectTimeout), TimeUnit.MILLISECONDS).readTimeout(ribbon.readTimeout(this.readTimeout), TimeUnit.MILLISECONDS).followRedirects(ribbon.isFollowRedirects(this.followRedirects));
    if (secure) {
        builder.followSslRedirects(ribbon.isFollowRedirects(this.followRedirects));
    }
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) IClientConfig(com.netflix.client.config.IClientConfig) RibbonProperties(org.springframework.cloud.netflix.ribbon.RibbonProperties)

Example 100 with Builder

use of okhttp3.Request.Builder in project spring-cloud-netflix by spring-cloud.

the class RibbonCommandContextTest method givenRibbonCommandContextIsSetup.

private void givenRibbonCommandContextIsSetup() {
    LinkedMultiValueMap headers = new LinkedMultiValueMap();
    LinkedMultiValueMap params = new LinkedMultiValueMap();
    RibbonRequestCustomizer requestCustomizer = new RibbonRequestCustomizer<Request.Builder>() {

        @Override
        public boolean accepts(Class builderClass) {
            return builderClass == Request.Builder.class;
        }

        @Override
        public void customize(Request.Builder builder) {
            builder.addHeader("from-customizer", "foo");
        }
    };
    ribbonCommandContext = new RibbonCommandContext("serviceId", HttpMethod.POST.toString(), "/my/route", true, headers, params, new ByteArrayInputStream(TEST_CONTENT), Lists.newArrayList(requestCustomizer));
}
Also used : LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ByteArrayInputStream(java.io.ByteArrayInputStream) Request(okhttp3.Request)

Aggregations

Request (okhttp3.Request)170 Response (okhttp3.Response)120 OkHttpClient (okhttp3.OkHttpClient)103 IOException (java.io.IOException)89 RequestBody (okhttp3.RequestBody)68 Test (org.junit.Test)68 File (java.io.File)36 MultipartBody (okhttp3.MultipartBody)36 HttpUrl (okhttp3.HttpUrl)34 Map (java.util.Map)31 MockResponse (okhttp3.mockwebserver.MockResponse)31 Call (okhttp3.Call)26 Interceptor (okhttp3.Interceptor)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)26 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)24 Builder (okhttp3.OkHttpClient.Builder)21 Retrofit (retrofit2.Retrofit)21 Builder (okhttp3.Request.Builder)19 FormBody (okhttp3.FormBody)18 ResponseBody (okhttp3.ResponseBody)18