Search in sources :

Example 16 with Builder

use of okhttp3.FormBody.Builder in project okhttp by square.

the class URLEncodingTest method backdoorUrlToUri.

private URI backdoorUrlToUri(URL url) throws Exception {
    final AtomicReference<URI> uriReference = new AtomicReference<>();
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    Internal.instance.setCache(builder, new InternalCache() {

        @Override
        public Response get(Request request) throws IOException {
            uriReference.set(request.url().uri());
            throw new UnsupportedOperationException();
        }

        @Override
        public CacheRequest put(Response response) throws IOException {
            return null;
        }

        @Override
        public void remove(Request request) throws IOException {
        }

        @Override
        public void update(Response cached, Response network) {
        }

        @Override
        public void trackConditionalCacheHit() {
        }

        @Override
        public void trackResponse(CacheStrategy cacheStrategy) {
        }
    });
    try {
        HttpURLConnection connection = new OkUrlFactory(builder.build()).open(url);
        connection.getResponseCode();
    } catch (Exception expected) {
        if (expected.getCause() instanceof URISyntaxException) {
            expected.printStackTrace();
        }
    }
    return uriReference.get();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) CacheRequest(okhttp3.internal.cache.CacheRequest) InternalCache(okhttp3.internal.cache.InternalCache) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Response(okhttp3.Response) OkUrlFactory(okhttp3.OkUrlFactory) HttpURLConnection(java.net.HttpURLConnection) CacheRequest(okhttp3.internal.cache.CacheRequest) CacheStrategy(okhttp3.internal.cache.CacheStrategy)

Example 17 with Builder

use of okhttp3.FormBody.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 18 with Builder

use of okhttp3.FormBody.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 19 with Builder

use of okhttp3.FormBody.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 20 with Builder

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

Aggregations

Request (okhttp3.Request)190 Response (okhttp3.Response)133 OkHttpClient (okhttp3.OkHttpClient)128 IOException (java.io.IOException)100 RequestBody (okhttp3.RequestBody)77 Test (org.junit.Test)68 File (java.io.File)42 HttpUrl (okhttp3.HttpUrl)40 MultipartBody (okhttp3.MultipartBody)40 Map (java.util.Map)34 MockResponse (okhttp3.mockwebserver.MockResponse)32 Call (okhttp3.Call)29 Retrofit (retrofit2.Retrofit)29 Interceptor (okhttp3.Interceptor)28 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)25 Builder (okhttp3.OkHttpClient.Builder)24 ResponseBody (okhttp3.ResponseBody)21 Provides (dagger.Provides)20 FormBody (okhttp3.FormBody)20