Search in sources :

Example 16 with Builder

use of okhttp3.HttpUrl.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 17 with Builder

use of okhttp3.HttpUrl.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)

Example 18 with Builder

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

the class CBLWebSocket method setupOkHttpClient.

// -------------------------------------------------------------------------
// private methods
// -------------------------------------------------------------------------
private OkHttpClient setupOkHttpClient() throws GeneralSecurityException {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // timeouts
    builder.connectTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS);
    // redirection
    builder.followRedirects(true).followSslRedirects(true);
    // authenticator
    Authenticator authenticator = setupAuthenticator();
    if (authenticator != null)
        builder.authenticator(authenticator);
    // trusted certificate (pinned certificate)
    setupTrustedCertificate(builder);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Authenticator(okhttp3.Authenticator)

Example 19 with Builder

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

the class CBLWebSocket method newRequest.

private Request newRequest() {
    Request.Builder builder = new Request.Builder();
    // Sets the URL target of this request.
    builder.url(uri.toString());
    // Set/update the "Host" header:
    String host = uri.getHost();
    if (uri.getPort() != -1)
        host = String.format(Locale.ENGLISH, "%s:%d", host, uri.getPort());
    builder.header("Host", host);
    // Construct the HTTP request:
    if (options != null) {
        // Extra Headers
        Map<String, Object> extraHeaders = (Map<String, Object>) options.get(kC4ReplicatorOptionExtraHeaders);
        if (extraHeaders != null) {
            for (Map.Entry<String, Object> entry : extraHeaders.entrySet()) {
                builder.header(entry.getKey(), entry.getValue().toString());
            }
        }
        // Cookies:
        String cookieString = (String) options.get(kC4ReplicatorOptionCookies);
        if (cookieString != null)
            builder.addHeader("Cookie", cookieString);
    }
    // Configure WebSocket related headers:
    String protocols = (String) options.get(kC4SocketOptionWSProtocols);
    if (protocols != null) {
        builder.header("Sec-WebSocket-Protocol", protocols);
    }
    return builder.build();
}
Also used : Request(okhttp3.Request) ByteString(okio.ByteString) HashMap(java.util.HashMap) Map(java.util.Map)

Example 20 with Builder

use of okhttp3.HttpUrl.Builder in project BBS-Android by bdpqchen.

the class CollectionClient method getUnSaveBuilder.

private static OkHttpClient.Builder getUnSaveBuilder() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager)

Aggregations

Request (okhttp3.Request)204 Response (okhttp3.Response)146 OkHttpClient (okhttp3.OkHttpClient)141 IOException (java.io.IOException)111 RequestBody (okhttp3.RequestBody)81 Test (org.junit.Test)75 HttpUrl (okhttp3.HttpUrl)47 File (java.io.File)42 MultipartBody (okhttp3.MultipartBody)40 MockResponse (okhttp3.mockwebserver.MockResponse)40 Map (java.util.Map)39 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)31 Call (okhttp3.Call)29 Interceptor (okhttp3.Interceptor)29 Retrofit (retrofit2.Retrofit)29 Builder (okhttp3.OkHttpClient.Builder)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)25 ResponseBody (okhttp3.ResponseBody)24 HashMap (java.util.HashMap)22 FormBody (okhttp3.FormBody)21