Search in sources :

Example 36 with Authenticator

use of okhttp3.Authenticator in project open-event-android by fossasia.

the class APIClient method getOpenEventAPI.

public static OpenEventAPI getOpenEventAPI() {
    if (openEventAPI == null) {
        OkHttpClient okHttpClient = okHttpClientBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)).authenticator(AuthUtil.getAuthenticator()).build();
        ObjectMapper objectMapper = getObjectMapper();
        Class[] classes = { Event.class, Track.class, Speaker.class, Sponsor.class, Session.class, Microlocation.class, User.class, FAQ.class, Notification.class, DiscountCode.class };
        openEventAPI = new Retrofit.Builder().client(okHttpClient).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(new JSONAPIConverterFactory(objectMapper, classes)).addConverterFactory(JacksonConverterFactory.create(getObjectMapper())).baseUrl(Urls.BASE_URL).build().create(OpenEventAPI.class);
    }
    return openEventAPI;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) JSONAPIConverterFactory(com.github.jasminb.jsonapi.retrofit.JSONAPIConverterFactory) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 37 with Authenticator

use of okhttp3.Authenticator in project LibreraReader by foobnix.

the class OPDS method getHttpResponse.

public static String getHttpResponse(String url) throws IOException {
    Request request = // 
    new Request.Builder().header("User-Agent", USER_AGENT).cacheControl(// 
    new CacheControl.Builder().maxAge(10, // 
    TimeUnit.MINUTES).build()).url(// 
    url).build();
    Response response = // 
    client.newCall(// 
    request).execute();
    LOG.d("Header: >>", url);
    LOG.d("Header: Status code:", response.code());
    for (int i = 0; i < response.headers().size(); i++) {
        String name = response.headers().name(i);
        String value = response.headers().value(i);
        LOG.d("Header: ", name, value);
    }
    if (response.code() == 401 && TxtUtils.isEmpty(TempHolder.get().login)) {
        return CODE_401;
    } else {
        Credentials credentials = new Credentials(TempHolder.get().login, TempHolder.get().password);
        final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(credentials);
        final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
        DispatchingAuthenticator authenticator = // 
        new DispatchingAuthenticator.Builder().with("digest", // 
        digestAuthenticator).with("basic", // 
        basicAuthenticator).build();
        client = // 
        builder.authenticator(// 
        new CachingAuthenticatorDecorator(authenticator, authCache)).addInterceptor(// 
        new AuthenticationCacheInterceptor(authCache)).build();
        response = client.newCall(request).execute();
        if (response.code() == 401) {
            return CODE_401;
        }
    }
    String string = response.body().string();
    return string;
}
Also used : Request(okhttp3.Request) CachingAuthenticatorDecorator(com.burgstaller.okhttp.CachingAuthenticatorDecorator) Response(okhttp3.Response) DispatchingAuthenticator(com.burgstaller.okhttp.DispatchingAuthenticator) BasicAuthenticator(com.burgstaller.okhttp.basic.BasicAuthenticator) DigestAuthenticator(com.burgstaller.okhttp.digest.DigestAuthenticator) AuthenticationCacheInterceptor(com.burgstaller.okhttp.AuthenticationCacheInterceptor) CacheControl(okhttp3.CacheControl) Credentials(com.burgstaller.okhttp.digest.Credentials)

Example 38 with Authenticator

use of okhttp3.Authenticator in project Douya by DreaminginCodeZH.

the class AuthenticationInterceptor method intercept.

@Override
public Response intercept(@NonNull Chain chain) throws IOException {
    Authenticator authenticator = getAuthenticator();
    Request request = authenticator.authenticate(chain.request());
    Response response = null;
    for (int retryCount = 0; retryCount < mMaxNumRetries; ++retryCount) {
        response = chain.proceed(request);
        if (response.isSuccessful()) {
            return response;
        }
        Request retryRequest = authenticator.retryAuthentication(response);
        if (retryRequest == null) {
            return response;
        }
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            responseBody.close();
        }
        if (retryRequest.body() instanceof UnrepeatableRequestBody) {
            throw new HttpRetryException("Cannot retry streamed HTTP body", response.code());
        }
        request = retryRequest;
    }
    return response;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) UnrepeatableRequestBody(okhttp3.internal.http.UnrepeatableRequestBody) HttpRetryException(java.net.HttpRetryException) ResponseBody(okhttp3.ResponseBody)

Example 39 with Authenticator

use of okhttp3.Authenticator in project Javacord by BtoBastian.

the class ProxyAuthenticator method systemDefaultAuthentication.

/**
 * Generates a {@code Basic} auth header with credentials from the system default authenticator.
 *
 * @param route    The route to which a request is done that needs to be authenticated.
 * @param request  The originating request that led to the authentication attempt.
 * @param response The response that demands authentication.
 * @return The {@code Basic} auth header.
 */
private Map<String, List<String>> systemDefaultAuthentication(Route route, Request request, Response response) {
    InetSocketAddress proxyAddress = (InetSocketAddress) route.getProxy().address();
    String host = proxyAddress.getHostString();
    InetAddress addr = proxyAddress.getAddress();
    int port = proxyAddress.getPort();
    URL url = route.getUrl();
    String protocol = url.getProtocol();
    return response.getChallenges("basic").filter(challenge -> challenge.getRealm().isPresent()).filter(challenge -> {
        String charset = challenge.getAuthParams().get("charset");
        return charset == null || charset.equalsIgnoreCase("UTF-8");
    }).map(challenge -> {
        String realm = challenge.getRealm().orElseThrow(AssertionError::new);
        PasswordAuthentication passwordAuthentication = java.net.Authenticator.requestPasswordAuthentication(host, addr, port, protocol, realm, challenge.getScheme(), url, java.net.Authenticator.RequestorType.PROXY);
        if (passwordAuthentication != null) {
            Charset charset = challenge.getAuthParams().containsKey("charset") ? StandardCharsets.UTF_8 : StandardCharsets.ISO_8859_1;
            return Credentials.basic(passwordAuthentication.getUserName(), String.valueOf(passwordAuthentication.getPassword()), charset);
        }
        return null;
    }).filter(Objects::nonNull).filter(credentials -> request.getHeaders("Proxy-Authorization").stream().noneMatch(credentials::equals)).findAny().map(credentials -> Collections.singletonMap("Proxy-Authorization", Arrays.asList(null, credentials))).orElse(null);
}
Also used : Arrays(java.util.Arrays) OkHttpResponseImpl(org.javacord.core.util.auth.OkHttpResponseImpl) Request(org.javacord.api.util.auth.Request) URL(java.net.URL) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) Route(org.javacord.api.util.auth.Route) InetAddress(java.net.InetAddress) Objects(java.util.Objects) Authenticator(org.javacord.api.util.auth.Authenticator) List(java.util.List) PasswordAuthentication(java.net.PasswordAuthentication) Charset(java.nio.charset.Charset) Map(java.util.Map) Response(org.javacord.api.util.auth.Response) OkHttpRequestImpl(org.javacord.core.util.auth.OkHttpRequestImpl) Collections(java.util.Collections) OkHttpRouteImpl(org.javacord.core.util.auth.OkHttpRouteImpl) InetSocketAddress(java.net.InetSocketAddress) Objects(java.util.Objects) Charset(java.nio.charset.Charset) InetAddress(java.net.InetAddress) URL(java.net.URL) PasswordAuthentication(java.net.PasswordAuthentication)

Example 40 with Authenticator

use of okhttp3.Authenticator in project okhttp by square.

the class AddressTest method differentProxySelectorsAreDifferent.

@Test
public void differentProxySelectorsAreDifferent() throws Exception {
    Address a = new Address("square.com", 80, dns, socketFactory, null, null, null, authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
    Address b = new Address("square.com", 80, dns, socketFactory, null, null, null, authenticator, null, protocols, connectionSpecs, new RecordingProxySelector());
    assertFalse(a.equals(b));
}
Also used : RecordingProxySelector(okhttp3.internal.http.RecordingProxySelector) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)37 Request (okhttp3.Request)27 OkHttpClient (okhttp3.OkHttpClient)26 Response (okhttp3.Response)24 MockResponse (okhttp3.mockwebserver.MockResponse)23 Authenticator (okhttp3.Authenticator)20 IOException (java.io.IOException)15 RecordingOkAuthenticator (okhttp3.internal.RecordingOkAuthenticator)15 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)13 Route (okhttp3.Route)12 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)9 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)8 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)7 InetSocketAddress (java.net.InetSocketAddress)7 RecordingAuthenticator (okhttp3.internal.RecordingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)5 InetAddress (java.net.InetAddress)5 Proxy (java.net.Proxy)5 Interceptor (okhttp3.Interceptor)5 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)5