Search in sources :

Example 21 with Route

use of okhttp3.Route in project hub-fortify-ssc-integration-service by blackducksoftware.

the class FortifyUnifiedLoginTokenApi method getHeader.

private static Builder getHeader(final PropertyConstants propertyConstants) {
    final HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    if (propertyConstants.getLogLevel().equalsIgnoreCase("INFO")) {
        logging.setLevel(Level.BASIC);
    } else {
        logging.setLevel(Level.BODY);
    }
    final OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
    okBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(final Route route, final Response response) throws IOException {
            final String credential = Credentials.basic(propertyConstants.getFortifyUserName(), propertyConstants.getFortifyPassword());
            if (credential.equals(response.request().header("Authorization"))) {
                try {
                    FortifyExceptionUtil.verifyFortifyResponseCode(response.code(), "Unauthorized access of Fortify Api");
                } catch (final IntegrationException e) {
                    throw new IOException(e);
                }
                return null;
            }
            return response.request().newBuilder().header("Authorization", credential).build();
        }
    });
    okBuilder.addInterceptor(logging);
    return okBuilder;
}
Also used : Builder(okhttp3.OkHttpClient.Builder) UnifiedLoginTokenResponse(com.blackducksoftware.integration.fortify.model.UnifiedLoginTokenResponse) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) IntegrationException(com.blackducksoftware.integration.exception.IntegrationException) Builder(okhttp3.OkHttpClient.Builder) Request(okhttp3.Request) IOException(java.io.IOException) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 22 with Route

use of okhttp3.Route in project autorest-clientruntime-for-java by Azure.

the class AzureTokenCredentials method applyCredentialsFilter.

@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
    clientBuilder.interceptors().add(new AzureTokenCredentialsInterceptor(this));
    clientBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String authenticateHeader = response.header("WWW-Authenticate");
            if (authenticateHeader != null && !authenticateHeader.isEmpty()) {
                Pattern pattern = Pattern.compile("resource=\"([a-zA-Z0-9.:/-_]+)\"");
                Matcher matcher = pattern.matcher(authenticateHeader);
                if (matcher.find()) {
                    String resource = matcher.group(1);
                    return response.request().newBuilder().header("Authorization", "Bearer " + getToken(resource)).build();
                }
            }
            // Otherwise cannot satisfy the challenge
            return null;
        }
    });
}
Also used : Response(okhttp3.Response) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Request(okhttp3.Request) IOException(java.io.IOException) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 23 with Route

use of okhttp3.Route in project nutch by apache.

the class OkHttp method setConf.

@Override
public void setConf(Configuration conf) {
    super.setConf(conf);
    // protocols in order of preference
    List<okhttp3.Protocol> protocols = new ArrayList<>();
    if (useHttp2) {
        protocols.add(okhttp3.Protocol.HTTP_2);
    }
    protocols.add(okhttp3.Protocol.HTTP_1_1);
    okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder().protocols(// 
    protocols).retryOnConnectionFailure(// 
    true).followRedirects(// 
    false).connectTimeout(timeout, TimeUnit.MILLISECONDS).writeTimeout(timeout, TimeUnit.MILLISECONDS).readTimeout(timeout, TimeUnit.MILLISECONDS);
    if (!tlsCheckCertificate) {
        builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }
    if (!accept.isEmpty()) {
        getCustomRequestHeaders().add(new String[] { "Accept", accept });
    }
    if (!acceptLanguage.isEmpty()) {
        getCustomRequestHeaders().add(new String[] { "Accept-Language", acceptLanguage });
    }
    if (!acceptCharset.isEmpty()) {
        getCustomRequestHeaders().add(new String[] { "Accept-Charset", acceptCharset });
    }
    if (useProxy) {
        Proxy proxy = new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort));
        String proxyUsername = conf.get("http.proxy.username");
        if (proxyUsername == null) {
            ProxySelector selector = new ProxySelector() {

                @SuppressWarnings("serial")
                private final List<Proxy> noProxyList = new ArrayList<Proxy>() {

                    {
                        add(Proxy.NO_PROXY);
                    }
                };

                @SuppressWarnings("serial")
                private final List<Proxy> proxyList = new ArrayList<Proxy>() {

                    {
                        add(proxy);
                    }
                };

                @Override
                public List<Proxy> select(URI uri) {
                    if (useProxy(uri)) {
                        return proxyList;
                    }
                    return noProxyList;
                }

                @Override
                public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                    LOG.error("Connection to proxy failed for {}: {}", uri, ioe);
                }
            };
            builder.proxySelector(selector);
        } else {
            /*
         * NOTE: the proxy exceptions list does NOT work with proxy
         * username/password because an okhttp3 bug
         * (https://github.com/square/okhttp/issues/3995) when using the
         * ProxySelector class with proxy auth. If a proxy username is present,
         * the configured proxy will be used for ALL requests.
         */
            if (proxyException.size() > 0) {
                LOG.warn("protocol-okhttp does not respect 'http.proxy.exception.list' setting when " + "'http.proxy.username' is set. This is a limitation of the current okhttp3 " + "implementation, see NUTCH-2636");
            }
            builder.proxy(proxy);
            String proxyPassword = conf.get("http.proxy.password");
            Authenticator proxyAuthenticator = new Authenticator() {

                @Override
                public Request authenticate(okhttp3.Route route, okhttp3.Response response) throws IOException {
                    String credential = okhttp3.Credentials.basic(proxyUsername, proxyPassword);
                    return response.request().newBuilder().header("Proxy-Authorization", credential).build();
                }
            };
            builder.proxyAuthenticator(proxyAuthenticator);
        }
    }
    if (storeIPAddress || storeHttpHeaders || storeHttpRequest) {
        builder.addNetworkInterceptor(new HTTPHeadersInterceptor());
    }
    // enable support for Brotli compression (Content-Encoding)
    builder.addInterceptor(BrotliInterceptor.INSTANCE);
    client = builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) URI(java.net.URI) HostnameVerifier(javax.net.ssl.HostnameVerifier) ProxySelector(java.net.ProxySelector) Response(org.apache.nutch.net.protocols.Response) Proxy(java.net.Proxy) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) Protocol(okhttp3.Protocol) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) Authenticator(okhttp3.Authenticator)

Example 24 with Route

use of okhttp3.Route in project rexxar-android by douban.

the class RexxarWebViewCore method loadUri.

/**
 * Rexxar entry
 * <p>
 * 如果map能够匹配上,则
 */
private void loadUri(final String uri, final UriLoadCallback callback, final boolean page) {
    LogUtils.i(TAG, "loadUri , uri = " + (null != uri ? uri : "null"));
    if (TextUtils.isEmpty(uri)) {
        throw new IllegalArgumentException("[RexxarWebView] [loadUri] uri can not be null");
    }
    final Route route;
    if (page) {
        route = RouteManager.getInstance().findRoute(uri);
    } else {
        route = RouteManager.getInstance().findPartialRoute(uri);
    }
    if (null == route) {
        LogUtils.i(TAG, "route not found");
        RouteManager.getInstance().refreshRouteFast(new RouteManager.RouteRefreshCallback() {

            @Override
            public void onSuccess(String data) {
                Route temp = page ? RouteManager.getInstance().findRoute(uri) : RouteManager.getInstance().findPartialRoute(uri);
                if (null == temp) {
                    // 没有找到通知外面route找不到
                    if (null != callback) {
                        callback.onFail(RxLoadError.ROUTE_NOT_FOUND);
                    }
                } else {
                    // 如果找到重新加载
                    loadUri(uri, callback, page);
                }
            }

            @Override
            public void onFail() {
                if (null != callback) {
                    callback.onFail(RxLoadError.ROUTE_NOT_FOUND);
                }
            }
        });
    } else {
        if (null != callback) {
            callback.onStartLoad();
        }
        if (CacheHelper.getInstance().cacheEnabled() && CacheHelper.getInstance().hasHtmlCached(route.getHtmlFile())) {
            // show cache
            doLoadCache(uri, route);
            if (null != callback) {
                callback.onSuccess();
            }
        } else {
            if (null != callback) {
                callback.onStartDownloadHtml();
            }
            HtmlHelper.prepareHtmlFile(route.getHtmlFile(), new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    if (null != callback) {
                        RxLoadError error = RxLoadError.HTML_DOWNLOAD_FAIL;
                        error.extra = route.getHtmlFile();
                        callback.onFail(error);
                    }
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    mMainHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            if (response.isSuccessful()) {
                                LogUtils.i(TAG, "download success");
                                final CacheEntry cacheEntry = CacheHelper.getInstance().findHtmlCache(route.getHtmlFile());
                                if (null != cacheEntry && cacheEntry.isValid()) {
                                    // show cache
                                    doLoadCache(uri, route);
                                    if (null != callback) {
                                        callback.onSuccess();
                                    }
                                }
                            } else {
                                if (null != callback) {
                                    RxLoadError error = RxLoadError.HTML_DOWNLOAD_FAIL;
                                    error.extra = route.getHtmlFile();
                                    callback.onFail(error);
                                }
                            }
                        }
                    });
                }
            });
        }
    }
}
Also used : Call(okhttp3.Call) IOException(java.io.IOException) CacheEntry(com.douban.rexxar.resourceproxy.cache.CacheEntry) Response(okhttp3.Response) Callback(okhttp3.Callback) RxLoadError(com.douban.rexxar.utils.RxLoadError) Route(com.douban.rexxar.route.Route) RouteManager(com.douban.rexxar.route.RouteManager)

Example 25 with Route

use of okhttp3.Route in project gh4a by slapperwan.

the class ServiceFactory method createLoginService.

public static LoginService createLoginService(String userName, String password, Optional.Supplier<String> otpCodeSupplier) {
    OkHttpClient.Builder clientBuilder = sApiHttpClient.newBuilder().addInterceptor(chain -> {
        String otpCode = otpCodeSupplier.get();
        Request request = chain.request();
        if (otpCode != null) {
            request = request.newBuilder().header("X-GitHub-OTP", otpCode).build();
        }
        return chain.proceed(request);
    }).authenticator((route, response) -> {
        if (response.priorResponse() != null) {
            return null;
        }
        return response.request().newBuilder().header("Authorization", Credentials.basic(userName, password)).build();
    });
    if (BuildConfig.DEBUG) {
        clientBuilder.addInterceptor(LOGGING_INTERCEPTOR);
        clientBuilder.addInterceptor(CACHE_STATUS_INTERCEPTOR);
    }
    clientBuilder.addInterceptor(CACHE_BYPASS_INTERCEPTOR);
    Retrofit retrofit = RETROFIT_BUILDER.baseUrl("https://api.github.com").client(clientBuilder.build()).build();
    return retrofit.create(LoginService.class);
}
Also used : Context(android.content.Context) Socket(java.net.Socket) Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) Cache(okhttp3.Cache) SSLSocket(javax.net.ssl.SSLSocket) TrustManager(javax.net.ssl.TrustManager) HashMap(java.util.HashMap) CacheControl(okhttp3.CacheControl) Single(io.reactivex.Single) RxJava2CallAdapterFactory(retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) ArrayList(java.util.ArrayList) GitHubPaginationInterceptor(com.meisolsson.githubsdk.core.GitHubPaginationInterceptor) InetAddress(java.net.InetAddress) Locale(java.util.Locale) ServiceGenerator(com.meisolsson.githubsdk.core.ServiceGenerator) ConnectionSpec(okhttp3.ConnectionSpec) Response(okhttp3.Response) Build(android.os.Build) POST(retrofit2.http.POST) Log(android.util.Log) Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) IOException(java.io.IOException) KeyStore(java.security.KeyStore) Credentials(okhttp3.Credentials) CrashReportingHelper(com.gh4a.utils.CrashReportingHelper) StringResponseConverterFactory(com.meisolsson.githubsdk.core.StringResponseConverterFactory) File(java.io.File) Retrofit(retrofit2.Retrofit) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) DELETE(retrofit2.http.DELETE) Optional(com.gh4a.utils.Optional) X509TrustManager(javax.net.ssl.X509TrustManager) TlsVersion(okhttp3.TlsVersion) MoshiConverterFactory(retrofit2.converter.moshi.MoshiConverterFactory) GET(retrofit2.http.GET) Path(retrofit2.http.Path) Body(retrofit2.http.Body) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request)

Aggregations

Response (okhttp3.Response)52 Request (okhttp3.Request)41 IOException (java.io.IOException)40 OkHttpClient (okhttp3.OkHttpClient)33 Route (okhttp3.Route)31 Proxy (java.net.Proxy)23 InetSocketAddress (java.net.InetSocketAddress)21 Authenticator (okhttp3.Authenticator)18 Test (org.junit.Test)17 Map (java.util.Map)16 List (java.util.List)13 HttpUrl (okhttp3.HttpUrl)13 RequestBody (okhttp3.RequestBody)13 Test (org.junit.jupiter.api.Test)13 Credentials (okhttp3.Credentials)11 ArrayList (java.util.ArrayList)10 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)10 File (java.io.File)9 URI (java.net.URI)9 URL (java.net.URL)9