Search in sources :

Example 36 with Builder

use of okhttp3.OkHttpClient.Builder in project kie-wb-common by kiegroup.

the class OpenShiftAccessInterfaceImpl method buildOpenShiftConfig.

// package-protected for junit testing purposes (from inside the package)
static OpenShiftConfig buildOpenShiftConfig(OpenShiftProviderConfig config) {
    OpenShiftConfigBuilder builder = new OpenShiftConfigBuilder(OpenShiftConfig.wrap(Config.autoConfigure()));
    /*
         * Kubernetes configuration properties; see io.fabric8.kubernetes.client.Config
         */
    String allProxy = trimToNull(config.getAllProxy());
    if (allProxy != null) {
        builder = builder.withHttpProxy(allProxy);
        builder = builder.withHttpsProxy(allProxy);
    }
    String httpProxy = trimToNull(config.getHttpProxy());
    if (httpProxy != null) {
        // NOTE: overrides allProxy above
        builder = builder.withHttpProxy(httpProxy);
    }
    String httpsProxy = trimToNull(config.getHttpsProxy());
    if (httpsProxy != null) {
        // NOTE: overrides allProxy above
        builder = builder.withHttpsProxy(httpsProxy);
    }
    String kubernetesApiVersion = trimToNull(config.getKubernetesApiVersion());
    if (kubernetesApiVersion != null) {
        builder = builder.withApiVersion(kubernetesApiVersion);
    }
    String kubernetesAuthBasicPassword = trimToNull(config.getKubernetesAuthBasicPassword());
    if (kubernetesAuthBasicPassword != null) {
        builder = builder.withPassword(kubernetesAuthBasicPassword);
    }
    String kubernetesAuthBasicUsername = trimToNull(config.getKubernetesAuthBasicUsername());
    if (kubernetesAuthBasicUsername != null) {
        builder = builder.withUsername(kubernetesAuthBasicUsername);
    }
    String kubernetesAuthToken = trimToNull(config.getKubernetesAuthToken());
    if (kubernetesAuthToken != null) {
        builder = builder.withOauthToken(kubernetesAuthToken);
    }
    String kubernetesCertsCaData = trimToNull(config.getKubernetesCertsCaData());
    if (kubernetesCertsCaData != null) {
        builder = builder.withCaCertData(kubernetesCertsCaData);
    }
    String kubernetesCertsCaFile = trimToNull(config.getKubernetesCertsCaFile());
    if (kubernetesCertsCaFile != null) {
        builder = builder.withCaCertFile(kubernetesCertsCaFile);
    }
    String kubernetesCertsClientData = trimToNull(config.getKubernetesCertsClientData());
    if (kubernetesCertsClientData != null) {
        builder = builder.withClientCertData(kubernetesCertsClientData);
    }
    String kubernetesCertsClientFile = trimToNull(config.getKubernetesCertsClientFile());
    if (kubernetesCertsClientFile != null) {
        builder = builder.withClientCertFile(kubernetesCertsClientFile);
    }
    String kubernetesCertsClientKeyAlgo = trimToNull(config.getKubernetesCertsClientKeyAlgo());
    if (kubernetesCertsClientKeyAlgo != null) {
        builder = builder.withClientKeyAlgo(kubernetesCertsClientKeyAlgo);
    }
    String kubernetesCertsClientKeyData = trimToNull(config.getKubernetesCertsClientKeyData());
    if (kubernetesCertsClientKeyData != null) {
        builder = builder.withClientKeyData(kubernetesCertsClientKeyData);
    }
    String kubernetesCertsClientKeyFile = trimToNull(config.getKubernetesCertsClientKeyFile());
    if (kubernetesCertsClientKeyFile != null) {
        builder = builder.withClientKeyFile(kubernetesCertsClientKeyFile);
    }
    String kubernetesCertsClientKeyPassphrase = trimToNull(config.getKubernetesCertsClientKeyPassphrase());
    if (kubernetesCertsClientKeyPassphrase != null) {
        builder = builder.withClientKeyPassphrase(kubernetesCertsClientKeyPassphrase);
    }
    String kubernetesConnectionTimeout = trimToNull(config.getKubernetesConnectionTimeout());
    if (kubernetesConnectionTimeout != null) {
        builder = builder.withConnectionTimeout(Integer.parseInt(kubernetesConnectionTimeout));
    }
    String kubernetesKeystoreFile = trimToNull(config.getKubernetesKeystoreFile());
    if (kubernetesKeystoreFile != null) {
        builder = builder.withKeyStoreFile(kubernetesKeystoreFile);
    }
    String kubernetesKeystorePassphrase = trimToNull(config.getKubernetesKeystorePassphrase());
    if (kubernetesKeystorePassphrase != null) {
        builder = builder.withKeyStorePassphrase(kubernetesKeystorePassphrase);
    }
    String kubernetesLoggingInterval = trimToNull(config.getKubernetesLoggingInterval());
    if (kubernetesLoggingInterval != null) {
        builder = builder.withLoggingInterval(Integer.parseInt(kubernetesLoggingInterval));
    }
    String kubernetesMaster = trimToNull(config.getKubernetesMaster());
    if (kubernetesMaster != null) {
        builder = builder.withMasterUrl(kubernetesMaster);
    }
    String kubernetesNamespace = trimToNull(config.getKubernetesNamespace());
    if (kubernetesNamespace != null) {
        builder = builder.withNamespace(kubernetesNamespace);
    }
    String kubernetesRequestTimeout = trimToNull(config.getKubernetesRequestTimeout());
    if (kubernetesRequestTimeout != null) {
        builder = builder.withRequestTimeout(Integer.parseInt(kubernetesRequestTimeout));
    }
    String kubernetesRollingTimeout = trimToNull(config.getKubernetesRollingTimeout());
    if (kubernetesRollingTimeout != null) {
        builder = builder.withRollingTimeout(Long.parseLong(kubernetesRollingTimeout));
    }
    String kubernetesScaleTimeout = trimToNull(config.getKubernetesScaleTimeout());
    if (kubernetesScaleTimeout != null) {
        builder = builder.withScaleTimeout(Long.parseLong(kubernetesScaleTimeout));
    }
    String kubernetesTlsVersions = trimToNull(config.getKubernetesTlsVersions());
    if (kubernetesTlsVersions != null) {
        String[] split = kubernetesTlsVersions.split(",");
        TlsVersion[] vers = new TlsVersion[split.length];
        for (int i = 0; i < split.length; i++) {
            vers[i] = TlsVersion.forJavaName(split[i]);
        }
        builder.withTlsVersions(vers);
    }
    String kubernetesTrustCertificates = trimToNull(config.getKubernetesTrustCertificates());
    if (kubernetesTrustCertificates != null) {
        builder = builder.withTrustCerts(Boolean.parseBoolean(kubernetesTrustCertificates));
    }
    String kubernetesTruststoreFile = trimToNull(config.getKubernetesTruststoreFile());
    if (kubernetesTruststoreFile != null) {
        builder = builder.withTrustStoreFile(kubernetesTruststoreFile);
    }
    String kubernetesTruststorePassphrase = trimToNull(config.getKubernetesTruststorePassphrase());
    if (kubernetesTruststorePassphrase != null) {
        builder = builder.withTrustStorePassphrase(kubernetesTruststorePassphrase);
    }
    String kubernetesUserAgent = trimToNull(config.getKubernetesUserAgent());
    if (kubernetesUserAgent != null) {
        builder = builder.withUserAgent(kubernetesUserAgent);
    }
    String kubernetesWatchReconnectInterval = trimToNull(config.getKubernetesWatchReconnectInterval());
    if (kubernetesWatchReconnectInterval != null) {
        builder = builder.withWatchReconnectInterval(Integer.parseInt(kubernetesWatchReconnectInterval));
    }
    String kubernetesWatchReconnectLimit = trimToNull(config.getKubernetesWatchReconnectLimit());
    if (kubernetesWatchReconnectLimit != null) {
        builder = builder.withWatchReconnectLimit(Integer.parseInt(kubernetesWatchReconnectLimit));
    }
    String kubernetesWebsocketPingInterval = trimToNull(config.getKubernetesWebsocketPingInterval());
    if (kubernetesWebsocketPingInterval != null) {
        builder = builder.withWebsocketPingInterval(Long.parseLong(kubernetesWebsocketPingInterval));
    }
    String kubernetesWebsocketTimeout = trimToNull(config.getKubernetesWebsocketTimeout());
    if (kubernetesWebsocketTimeout != null) {
        builder = builder.withWebsocketTimeout(Long.parseLong(kubernetesWebsocketTimeout));
    }
    String noProxy = trimToNull(config.getNoProxy());
    if (noProxy != null) {
        builder = builder.withNoProxy(noProxy.split(","));
    }
    String proxyPassword = trimToNull(config.getProxyPassword());
    if (proxyPassword != null) {
        builder = builder.withProxyPassword(proxyPassword);
    }
    String proxyUsername = trimToNull(config.getProxyUsername());
    if (proxyUsername != null) {
        builder = builder.withProxyUsername(proxyUsername);
    }
    /*
         * OpenShift configuration properties; see io.fabric8.openshift.client.OpenShiftConfig
         */
    String kubernetesOapiVersion = trimToNull(config.getKubernetesOapiVersion());
    if (kubernetesOapiVersion != null) {
        builder = builder.withOapiVersion(kubernetesOapiVersion);
    }
    String openshiftBuildTimeout = trimToNull(config.getOpenshiftBuildTimeout());
    if (openshiftBuildTimeout != null) {
        builder = builder.withBuildTimeout(Long.parseLong(openshiftBuildTimeout));
    }
    String openshiftUrl = trimToNull(config.getOpenshiftUrl());
    if (openshiftUrl != null) {
        // The OPENSHIFT_URL environment variable may be set to the root url (i.e. without the '/oapi/version' path) in some configurations
        if (isRootUrl(openshiftUrl)) {
            openshiftUrl = URLUtils.join(openshiftUrl, "oapi", builder.getOapiVersion());
        }
        builder = builder.withOpenShiftUrl(openshiftUrl);
    } else {
        builder.withOpenShiftUrl(URLUtils.join(builder.getMasterUrl(), "oapi", builder.getOapiVersion()));
    }
    return builder.build();
}
Also used : TlsVersion(okhttp3.TlsVersion) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder)

Example 37 with Builder

use of okhttp3.OkHttpClient.Builder in project run-wallet-android by runplay.

the class RunIotaAPICore method postConstruct.

/**
 * added header for IRI
 */
private void postConstruct() {
    boolean USE_AUTH = false;
    // if(host.contains(".runplay.com") || host.contains(".runpg.com"))
    // USE_AUTH=true;
    final String nodeUrl = protocol + "://" + host + ":" + port;
    if (USE_AUTH) {
        // Log.e("IRI-CONNECT","Using Auth OK");
        String creds = Base64.encodeToString((uname + ":" + upassword).getBytes(), false);
        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
        OkHttpClient client = builder.readTimeout(5000, TimeUnit.SECONDS).addInterceptor(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request newRequest;
                newRequest = request.newBuilder().addHeader(X_IOTA_API_VERSION_HEADER_NAME, X_IOTA_API_VERSION_HEADER_VALUE).addHeader("Authorization", "Basic " + creds).build();
                return chain.proceed(newRequest);
            }
        }).connectTimeout(5000, TimeUnit.SECONDS).build();
        // use client to create Retrofit service
        final Retrofit retrofit = new Retrofit.Builder().baseUrl(nodeUrl).addConverterFactory(GsonConverterFactory.create()).client(client).build();
        service = retrofit.create(IotaAPIService.class);
    } else {
        // Log.e("IRI-CONNECT","NOOTTTTT Using Auth");
        final OkHttpClient client = new OkHttpClient.Builder().readTimeout(5000, TimeUnit.SECONDS).addInterceptor(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request newRequest;
                newRequest = request.newBuilder().addHeader(X_IOTA_API_VERSION_HEADER_NAME, X_IOTA_API_VERSION_HEADER_VALUE).build();
                return chain.proceed(newRequest);
            }
        }).connectTimeout(5000, TimeUnit.SECONDS).build();
        // use client to create Retrofit service
        final Retrofit retrofit = new Retrofit.Builder().baseUrl(nodeUrl).addConverterFactory(GsonConverterFactory.create()).client(client).build();
        service = retrofit.create(IotaAPIService.class);
    }
    // Create OkHttpBuilder
    log.debug("Jota-API Java proxy pointing to node url: '{}'", nodeUrl);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Interceptor(okhttp3.Interceptor)

Example 38 with Builder

use of okhttp3.OkHttpClient.Builder in project instructure-android by instructure.

the class RequestInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Request.Builder builder = request.newBuilder();
    final String token = ApiPrefs.getToken();
    final String userAgent = ApiPrefs.getUserAgent();
    final String domain = ApiPrefs.getFullDomain();
    /* Nearly all requests are instantiated using RestBuilder and will have been tagged with
        a RestParams instance. Here we will attempt to retrieve it, but if unsuccessful we will
        fall back to a new RestParams instance with default values. */
    RestParams params;
    if (request.tag() != null && request.tag() instanceof RestParams) {
        params = (RestParams) request.tag();
    } else {
        params = new RestParams.Builder().build();
    }
    // Set the UserAgent
    if (!userAgent.equals("")) {
        builder.addHeader("User-Agent", userAgent);
    }
    // Authenticate if possible
    if (!params.shouldIgnoreToken() && !token.equals("")) {
        builder.addHeader("Authorization", "Bearer " + token);
    }
    // Add Accept-Language header for a11y
    builder.addHeader("accept-language", getAcceptedLanguageString());
    if (!APIHelper.hasNetworkConnection() || params.isForceReadFromCache()) {
        // Offline or only want cached data
        builder.cacheControl(CacheControl.FORCE_CACHE);
    } else if (params.isForceReadFromNetwork()) {
        // Typical from a pull-to-refresh
        builder.cacheControl(CacheControl.FORCE_NETWORK);
    }
    // Fun Fact: HTTP referer (originally a misspelling of referrer) is an HTTP header field that identifies
    // the address of the webpage that linked to the resource being requested
    // Source: https://en.wikipedia.org/wiki/HTTP_referer
    // Institutions need the referrer for a variety of reasons - mostly for restricted content
    // Strip out non-ascii characters, otherwise addHeader may throw an exception
    builder.addHeader("Referer", domain.replaceAll("[^\\x20-\\x7e]", ""));
    request = builder.build();
    // Masquerade if necessary
    if (ApiPrefs.isMasquerading()) {
        HttpUrl url = request.url().newBuilder().addQueryParameter("as_user_id", Long.toString(ApiPrefs.getMasqueradeId())).build();
        request = request.newBuilder().url(url).build();
    }
    if (params.usePerPageQueryParam()) {
        HttpUrl url = request.url().newBuilder().addQueryParameter("per_page", Integer.toString(ApiPrefs.getPerPageCount())).build();
        request = request.newBuilder().url(url).build();
    }
    return chain.proceed(request);
}
Also used : RestParams(com.instructure.canvasapi2.builders.RestParams) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl)

Example 39 with Builder

use of okhttp3.OkHttpClient.Builder in project brave by openzipkin.

the class TracingInterceptor method intercept.

@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request.Builder builder = chain.request().newBuilder();
    Span span = clientHandler.handleSend(injector, builder, chain.request());
    Response response = null;
    Throwable error = null;
    try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
        return response = chain.proceed(builder.build());
    } catch (IOException | RuntimeException | Error e) {
        error = e;
        throw e;
    } finally {
        clientHandler.handleReceive(response, error, span);
    }
}
Also used : Response(okhttp3.Response) Tracer(brave.Tracer) Request(okhttp3.Request) IOException(java.io.IOException) Span(brave.Span)

Example 40 with Builder

use of okhttp3.OkHttpClient.Builder in project YhLibraryForAndroid by android-coco.

the class LoggerInterceptor method logForResponse.

private Response logForResponse(Response response, long duration) {
    try {
        // ===>response LogUtils
        LogUtils.e(tag, "============服务器回复'LogUtils============开始");
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        LogUtils.e(tag, "请求url : " + clone.request().url());
        LogUtils.e(tag, "请求code : " + clone.code());
        LogUtils.e(tag, "请求协议protocol : " + clone.protocol());
        if (!TextUtils.isEmpty(clone.message())) {
            LogUtils.e(tag, "是否成功 : " + clone.message());
            if (showResponse) {
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        LogUtils.e(tag, "响应主体的类型 : " + mediaType.toString());
                        if (isText(mediaType)) {
                            String resp = body.string();
                            LogUtils.e(tag, "响应主体的内容 : " + resp);
                            body = ResponseBody.create(mediaType, resp);
                            LogUtils.e(tag, "============服务器回复'LogUtils==========结束" + duration + "毫秒");
                            return response.newBuilder().body(body).build();
                        } else {
                            LogUtils.e(tag, "响应主体的内容 : " + " 也许[文件部分],太大了太大了,忽略了!");
                        }
                    }
                }
            }
        }
        LogUtils.e(tag, "============服务器回复'LogUtils==========结束" + duration + "毫秒");
    } catch (Exception e) {
        LogUtils.e(tag, "============服务器回复打印异常:" + e.getMessage());
    }
    return response;
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

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