Search in sources :

Example 51 with Request

use of okhttp3.Request in project azure-sdk-for-java by Azure.

the class KeyVaultCredentials method applyCredentialsFilter.

@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
    clientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            HttpUrl url = chain.request().url();
            Map<String, String> challengeMap = cache.getCachedChallenge(url);
            if (challengeMap != null) {
                // Get the bearer token
                String credential = getAuthenticationCredentials(challengeMap);
                Request newRequest = chain.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
                return chain.proceed(newRequest);
            } else {
                // response
                return chain.proceed(chain.request());
            }
        }
    });
    // Caches the challenge for failed request and re-send the request with
    // access token.
    clientBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            // if challenge is not cached then extract and cache it
            String authenticateHeader = response.header(WWW_AUTHENTICATE);
            Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
            // Cache the challenge
            cache.addCachedChallenge(response.request().url(), challengeMap);
            // Get the bearer token from the callback by providing the
            // challenges
            String credential = getAuthenticationCredentials(challengeMap);
            if (credential == null) {
                return null;
            }
            // be cached anywhere in our code.
            return response.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
        }
    });
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor) Map(java.util.Map) HashMap(java.util.HashMap) HttpUrl(okhttp3.HttpUrl) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 52 with Request

use of okhttp3.Request in project azure-sdk-for-java by Azure.

the class MockIntegrationTestBase method recordRequestAndResponse.

private Response recordRequestAndResponse(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();
    NetworkCallRecord networkCallRecord = new NetworkCallRecord();
    networkCallRecord.Headers = new HashMap<>();
    try {
        if (request.header("Content-Type") != null) {
            networkCallRecord.Headers.put("Content-Type", request.header("Content-Type"));
        }
        if (request.header("x-ms-version") != null) {
            networkCallRecord.Headers.put("x-ms-version", request.header("x-ms-version"));
        }
        if (request.header("User-Agent") != null) {
            networkCallRecord.Headers.put("User-Agent", request.header("User-Agent"));
        }
        networkCallRecord.Method = request.method();
        networkCallRecord.Uri = applyRegex(request.url().toString().replaceAll("\\?$", ""));
    } catch (Exception e) {
    }
    Response response = chain.proceed(chain.request());
    networkCallRecord.Response = new HashMap<>();
    try {
        networkCallRecord.Response.put("StatusCode", Integer.toString(response.code()));
        extractResponseData(networkCallRecord.Response, response);
        // remove pre-added header if this is a waiting or redirection
        if (networkCallRecord.Response.get("Body").contains("<Status>InProgress</Status>") || Integer.parseInt(networkCallRecord.Response.get("StatusCode")) == HttpStatus.SC_TEMPORARY_REDIRECT) {
        } else {
            synchronized (testRecord.networkCallRecords) {
                testRecord.networkCallRecords.add(networkCallRecord);
            }
        }
    } catch (Exception e) {
    }
    return response;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException)

Example 53 with Request

use of okhttp3.Request in project azure-sdk-for-java by Azure.

the class MockIntegrationTestBase method registerRecordedResponse.

private synchronized Response registerRecordedResponse(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();
    String url = request.url().toString();
    url = applyRegex(url);
    try {
        synchronized (testRecord.networkCallRecords) {
            registerStub(request.method(), url);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return chain.proceed(chain.request());
}
Also used : Request(okhttp3.Request) IOException(java.io.IOException)

Example 54 with Request

use of okhttp3.Request in project Gradle-demo by Arisono.

the class OkhttpUtils method sendGetHttp.

/** 
	 * get http 
	 * @param url
	 * @param tag
	 */
public static void sendGetHttp(String url, Map<String, Object> params, String cookies, String tag) {
    StringBuilder buf = new StringBuilder(url);
    if (params != null) {
        if (!params.isEmpty()) {
            if (url.indexOf("?") == -1)
                buf.append("?");
            else if (!url.endsWith("&"))
                buf.append("&");
            Iterator<Map.Entry<String, Object>> entries = params.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, Object> entry = entries.next();
                buf.append(String.valueOf(entry.getKey())).append("=").append(String.valueOf(entry.getValue())).append("&");
            }
            buf.deleteCharAt(buf.length() - 1);
        }
    }
    Request request = new Request.Builder().url(buf.toString()).addHeader("content-type", "text/html;charset:utf-8").addHeader("Cookie", "12").build();
    OkhttpUtils.println(tag + ":" + buf.toString());
    OkhttpUtils.client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String requestJson;
            requestJson = OkhttpUtils.getResponseString(response);
            OkhttpUtils.println(requestJson);
            RxBus.getInstance().send(tag + ":" + requestJson);
        }

        @Override
        public void onFailure(Call call, IOException e) {
            OkhttpUtils.onFailurePrintln(call, e, this);
        }
    });
}
Also used : Call(okhttp3.Call) Builder(okhttp3.FormBody.Builder) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) Map(java.util.Map)

Example 55 with Request

use of okhttp3.Request in project Gradle-demo by Arisono.

the class RetryIntercepter method intercept.

@SuppressWarnings("resource")
@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = chain.proceed(request);
    try {
        // OkhttpUtils.println("重试拦截器:"+response.isSuccessful());
        while (!response.isSuccessful() && retryNum < maxRetry) {
            retryNum++;
            response = chain.proceed(request);
        }
    } catch (ConnectException e) {
        OkhttpUtils.println("服务器拒绝连接.....");
    } catch (IOException e) {
        OkhttpUtils.println("服务器拒绝连接.....");
    }
    return response;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) ConnectException(java.net.ConnectException)

Aggregations

Request (okhttp3.Request)1552 Response (okhttp3.Response)1090 Test (org.junit.Test)948 IOException (java.io.IOException)624 MockResponse (okhttp3.mockwebserver.MockResponse)560 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)556 OkHttpClient (okhttp3.OkHttpClient)343 RequestBody (okhttp3.RequestBody)281 Call (okhttp3.Call)255 ResponseBody (okhttp3.ResponseBody)252 HttpUrl (okhttp3.HttpUrl)186 Test (org.junit.jupiter.api.Test)158 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)142 Buffer (okio.Buffer)138 List (java.util.List)114 Callback (okhttp3.Callback)114 File (java.io.File)105 URI (java.net.URI)101 InputStream (java.io.InputStream)99 JSONObject (org.json.JSONObject)96