Search in sources :

Example 21 with Builder

use of okhttp3.OkHttpClient.Builder in project java-cloudant by cloudant.

the class HttpProxyTest method proxiedRequest.

/**
 * This test validates that a request can successfully traverse a proxy to our mock server.
 */
@TestTemplate
public void proxiedRequest(final boolean okUsable, final boolean useSecureProxy, final boolean useHttpsServer, final boolean useProxyAuth) throws Exception {
    // mock a 200 OK
    server.setDispatcher(new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse();
        }
    });
    InetSocketAddress address = proxy.getListenAddress();
    URL proxyUrl = new URL((useSecureProxy) ? "https" : "http", address.getHostName(), address.getPort(), "/");
    ClientBuilder builder = CloudantClientHelper.newMockWebServerClientBuilder(server).proxyURL(proxyUrl);
    if (useProxyAuth) {
        builder.proxyUser(mockProxyUser).proxyPassword(mockProxyPass);
    }
    // We don't use SSL authentication for this test
    CloudantClient client = builder.disableSSLAuthentication().build();
    String response = client.executeRequest(Http.GET(client.getBaseUri())).responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");
    // if it wasn't a 20x then an exception should have been thrown by now
    RecordedRequest request = server.takeRequest(10, TimeUnit.SECONDS);
    assertNotNull(request);
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) CloudantClient(com.cloudant.client.api.CloudantClient) InetSocketAddress(java.net.InetSocketAddress) Dispatcher(okhttp3.mockwebserver.Dispatcher) URL(java.net.URL) ClientBuilder(com.cloudant.client.api.ClientBuilder) TestTemplate(org.junit.jupiter.api.TestTemplate)

Example 22 with Builder

use of okhttp3.OkHttpClient.Builder in project rexxar-android by douban.

the class RouteFetcher method remoteFile.

/**
 * http协议
 *
 * @param callback
 */
private static void remoteFile(final RouteManager.RouteRefreshCallback callback) {
    try {
        Request.Builder builder = new Request.Builder().url(sRouteApi);
        // user-agent
        builder.addHeader("User-Agent", Rexxar.getUserAgent());
        Rexxar.getOkHttpClient().newCall(builder.build()).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.i(TAG, e.getMessage());
                notifyFail(callback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String data = IOUtils.toString(response.body().byteStream());
                    notifySuccess(callback, data);
                } else {
                    notifyFail(callback);
                }
            }
        });
    } catch (Exception e) {
        LogUtils.e(TAG, e.getMessage());
        notifyFail(callback);
    }
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Callback(okhttp3.Callback) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException)

Example 23 with Builder

use of okhttp3.OkHttpClient.Builder in project rexxar-android by douban.

the class AuthInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String url = request.url().toString();
    if (TextUtils.isEmpty(url)) {
        return null;
    }
    Request.Builder builder = request.newBuilder();
    builder.header("Authorization", "123456789");
    return chain.proceed(builder.build());
}
Also used : Request(okhttp3.Request)

Example 24 with Builder

use of okhttp3.OkHttpClient.Builder in project nifi by apache.

the class QueryElasticsearchHttp method buildRequestURL.

private URL buildRequestURL(String baseUrl, String query, String index, String type, String fields, String sort, int pageSize, int fromIndex, ProcessContext context) throws MalformedURLException {
    if (StringUtils.isEmpty(baseUrl)) {
        throw new MalformedURLException("Base URL cannot be null");
    }
    HttpUrl.Builder builder = HttpUrl.parse(baseUrl).newBuilder();
    builder.addPathSegment((StringUtils.isEmpty(index)) ? "_all" : index);
    if (!StringUtils.isEmpty(type)) {
        builder.addPathSegment(type);
    }
    builder.addPathSegment("_search");
    builder.addQueryParameter(QUERY_QUERY_PARAM, query);
    builder.addQueryParameter(SIZE_QUERY_PARAM, String.valueOf(pageSize));
    builder.addQueryParameter(FROM_QUERY_PARAM, String.valueOf(fromIndex));
    if (!StringUtils.isEmpty(fields)) {
        String trimmedFields = Stream.of(fields.split(",")).map(String::trim).collect(Collectors.joining(","));
        builder.addQueryParameter(FIELD_INCLUDE_QUERY_PARAM, trimmedFields);
    }
    if (!StringUtils.isEmpty(sort)) {
        String trimmedFields = Stream.of(sort.split(",")).map(String::trim).collect(Collectors.joining(","));
        builder.addQueryParameter(SORT_QUERY_PARAM, trimmedFields);
    }
    // Find the user-added properties and set them as query parameters on the URL
    for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
        PropertyDescriptor pd = property.getKey();
        if (pd.isDynamic()) {
            if (property.getValue() != null) {
                builder.addQueryParameter(pd.getName(), context.getProperty(pd).evaluateAttributeExpressions().getValue());
            }
        }
    }
    return builder.build().url();
}
Also used : MalformedURLException(java.net.MalformedURLException) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) HashMap(java.util.HashMap) Map(java.util.Map) HttpUrl(okhttp3.HttpUrl)

Example 25 with Builder

use of okhttp3.OkHttpClient.Builder in project couchbase-lite-android by couchbase.

the class ReplicatorWithSyncGatewayDBTest method sendRequestToEndpoint.

JSONObject sendRequestToEndpoint(URLEndpoint endpoint, String method, String path, String mediaType, byte[] body) throws Exception {
    URI endpointURI = endpoint.getURL();
    String _scheme = endpointURI.getScheme().equals(URLEndpoint.kURLEndpointTLSScheme) ? "https" : "http";
    String _host = endpointURI.getHost();
    int _port = endpointURI.getPort() + 1;
    path = (path != null) ? (path.startsWith("/") ? path : "/" + path) : "";
    String _path = String.format(Locale.ENGLISH, "%s%s", endpointURI.getPath(), path);
    URI uri = new URI(_scheme, null, _host, _port, _path, null, null);
    OkHttpClient client = new OkHttpClient();
    okhttp3.Request.Builder builder = new okhttp3.Request.Builder().url(uri.toURL());
    RequestBody requestBody = null;
    if (body != null && body instanceof byte[])
        requestBody = RequestBody.create(MediaType.parse(mediaType), body);
    builder.method(method, requestBody);
    okhttp3.Request request = builder.build();
    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        Log.i(TAG, "Send request succeeded; URL=<%s>, Method=<%s>, Status=%d", uri, method, response.code());
        return new JSONObject(response.body().string());
    } else {
        // error
        Log.e(TAG, "Failed to send request; URL=<%s>, Method=<%s>, Status=%d, Error=%s", uri, method, response.code(), response.message());
        return null;
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) URI(java.net.URI) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)186 Response (okhttp3.Response)128 OkHttpClient (okhttp3.OkHttpClient)116 IOException (java.io.IOException)97 RequestBody (okhttp3.RequestBody)76 Test (org.junit.Test)68 File (java.io.File)41 MultipartBody (okhttp3.MultipartBody)40 HttpUrl (okhttp3.HttpUrl)39 Map (java.util.Map)34 MockResponse (okhttp3.mockwebserver.MockResponse)32 Call (okhttp3.Call)28 Interceptor (okhttp3.Interceptor)28 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)26 Retrofit (retrofit2.Retrofit)26 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)25 Builder (okhttp3.OkHttpClient.Builder)23 FormBody (okhttp3.FormBody)20 ResponseBody (okhttp3.ResponseBody)20 Builder (okhttp3.Request.Builder)19