Search in sources :

Example 31 with Credentials

use of okhttp3.Credentials 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 32 with Credentials

use of okhttp3.Credentials in project drill by apache.

the class SimpleHttp method setupHttpClient.

/**
 * Configures the OkHTTP3 server object with configuration info from the user.
 *
 * @return OkHttpClient configured server
 */
private OkHttpClient setupHttpClient() {
    Builder builder = new OkHttpClient.Builder();
    // Set up the HTTP Cache.   Future possibilities include making the cache size and retention configurable but
    // right now it is on or off.  The writer will write to the Drill temp directory if it is accessible and
    // output a warning if not.
    HttpStoragePluginConfig config = scanDefn.tableSpec().config();
    if (config.cacheResults()) {
        setupCache(builder);
    }
    HttpApiConfig apiConfig = scanDefn.tableSpec().connectionConfig();
    // If OAuth information is provided, we will assume that the user does not want to use
    // basic authentication
    HttpOAuthConfig oAuthConfig = scanDefn.tableSpec().config().oAuthConfig();
    if (oAuthConfig != null) {
        // Add interceptors for OAuth2
        logger.debug("Adding OAuth2 Interceptor");
        AccessTokenRepository repository = new AccessTokenRepository(proxyConfig, config, tokenTable);
        builder.authenticator(new AccessTokenAuthenticator(repository));
        builder.addInterceptor(new AccessTokenInterceptor(repository));
    } else if (apiConfig.authType().equalsIgnoreCase("basic")) {
        // If the API uses basic authentication add the authentication code.
        logger.debug("Adding Interceptor");
        UsernamePasswordCredentials credentials = apiConfig.getUsernamePasswordCredentials();
        builder.addInterceptor(new BasicAuthInterceptor(credentials.getUsername(), credentials.getPassword()));
    }
    // Set timeouts
    int timeout = Math.max(1, config.timeout());
    builder.connectTimeout(timeout, TimeUnit.SECONDS);
    builder.writeTimeout(timeout, TimeUnit.SECONDS);
    builder.readTimeout(timeout, TimeUnit.SECONDS);
    // Sourced from https://stackoverflow.com/questions/60110848/how-to-disable-ssl-verification
    if (!apiConfig.verifySSLCert()) {
        try {
            TrustManager[] trustAllCerts = getAllTrustingTrustManager();
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            HostnameVerifier verifier = (hostname, session) -> true;
            builder.hostnameVerifier(verifier);
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            logger.error("Error when configuring Drill not to verify SSL certs. {}", e.getMessage());
        }
    }
    // Set the proxy configuration
    addProxyInfo(builder, proxyConfig);
    return builder.build();
}
Also used : HttpSubScan(org.apache.drill.exec.store.http.HttpSubScan) X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) Cache(okhttp3.Cache) URLDecoder(java.net.URLDecoder) UserException(org.apache.drill.common.exceptions.UserException) LoggerFactory(org.slf4j.LoggerFactory) TrustManager(javax.net.ssl.TrustManager) HttpOAuthConfig(org.apache.drill.exec.store.http.HttpOAuthConfig) StringUtils(org.apache.commons.lang3.StringUtils) FormBody(okhttp3.FormBody) PersistentTokenTable(org.apache.drill.exec.oauth.PersistentTokenTable) Matcher(java.util.regex.Matcher) Proxy(java.net.Proxy) Map(java.util.Map) HostnameVerifier(javax.net.ssl.HostnameVerifier) Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) HttpMethod(org.apache.drill.exec.store.http.HttpApiConfig.HttpMethod) HttpApiConfig(org.apache.drill.exec.store.http.HttpApiConfig) KeyManagementException(java.security.KeyManagementException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) AccessTokenAuthenticator(org.apache.drill.exec.store.http.oauth.AccessTokenAuthenticator) Objects(java.util.Objects) List(java.util.List) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AccessTokenInterceptor(org.apache.drill.exec.store.http.oauth.AccessTokenInterceptor) Pattern(java.util.regex.Pattern) HttpUrl(okhttp3.HttpUrl) NotNull(org.jetbrains.annotations.NotNull) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Builder(okhttp3.OkHttpClient.Builder) StoragePluginRegistry(org.apache.drill.exec.store.StoragePluginRegistry) CustomErrorContext(org.apache.drill.common.exceptions.CustomErrorContext) ArrayList(java.util.ArrayList) UsernamePasswordCredentials(org.apache.drill.exec.store.security.UsernamePasswordCredentials) AccessTokenRepository(org.apache.drill.exec.store.http.oauth.AccessTokenRepository) Response(okhttp3.Response) Logger(org.slf4j.Logger) IOException(java.io.IOException) CaseInsensitiveMap(org.apache.drill.common.map.CaseInsensitiveMap) Paginator(org.apache.drill.exec.store.http.paginator.Paginator) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) HttpStoragePluginConfig(org.apache.drill.exec.store.http.HttpStoragePluginConfig) InputStream(java.io.InputStream) AccessTokenInterceptor(org.apache.drill.exec.store.http.oauth.AccessTokenInterceptor) HttpApiConfig(org.apache.drill.exec.store.http.HttpApiConfig) Builder(okhttp3.OkHttpClient.Builder) AccessTokenRepository(org.apache.drill.exec.store.http.oauth.AccessTokenRepository) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) UsernamePasswordCredentials(org.apache.drill.exec.store.security.UsernamePasswordCredentials) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) HttpOAuthConfig(org.apache.drill.exec.store.http.HttpOAuthConfig) AccessTokenAuthenticator(org.apache.drill.exec.store.http.oauth.AccessTokenAuthenticator) HttpStoragePluginConfig(org.apache.drill.exec.store.http.HttpStoragePluginConfig) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 33 with Credentials

use of okhttp3.Credentials in project AntennaPod by AntennaPod.

the class AntennapodHttpClient method newBuilder.

/**
 * Creates a new HTTP client.  Most users should just use
 * getHttpClient() to get the standard AntennaPod client,
 * but sometimes it's necessary for others to have their own
 * copy so that the clients don't share state.
 * @return http client
 */
@NonNull
public static OkHttpClient.Builder newBuilder() {
    Log.d(TAG, "Creating new instance of HTTP client");
    System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // detect 301 Moved permanently and 308 Permanent Redirect
    builder.networkInterceptors().add(chain -> {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == HttpURLConnection.HTTP_MOVED_PERM || response.code() == StatusLine.HTTP_PERM_REDIRECT) {
            String location = response.header("Location");
            if (location == null) {
                return response;
            }
            if (location.startsWith("/")) {
                // URL is not absolute, but relative
                HttpUrl url = request.url();
                location = url.scheme() + "://" + url.host() + location;
            } else if (!location.toLowerCase().startsWith("http://") && !location.toLowerCase().startsWith("https://")) {
                // Reference is relative to current path
                HttpUrl url = request.url();
                String path = url.encodedPath();
                String newPath = path.substring(0, path.lastIndexOf("/") + 1) + location;
                location = url.scheme() + "://" + url.host() + newPath;
            }
            try {
                DBWriter.updateFeedDownloadURL(request.url().toString(), location).get();
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
        return response;
    });
    builder.interceptors().add(new BasicAuthorizationInterceptor());
    builder.networkInterceptors().add(new UserAgentInterceptor());
    // set cookie handler
    CookieManager cm = new CookieManager();
    cm.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
    builder.cookieJar(new JavaNetCookieJar(cm));
    // set timeouts
    builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    // 20MB
    builder.cache(new Cache(cacheDirectory, 20L * 1000000));
    // configure redirects
    builder.followRedirects(true);
    builder.followSslRedirects(true);
    ProxyConfig config = UserPreferences.getProxyConfig();
    if (config.type != Proxy.Type.DIRECT && !TextUtils.isEmpty(config.host)) {
        int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
        SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
        builder.proxy(new Proxy(config.type, address));
        if (!TextUtils.isEmpty(config.username) && config.password != null) {
            builder.proxyAuthenticator((route, response) -> {
                String credentials = Credentials.basic(config.username, config.password);
                return response.request().newBuilder().header("Proxy-Authorization", credentials).build();
            });
        }
    }
    SslClientSetup.installCertificates(builder);
    return builder;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) UserAgentInterceptor(de.danoeh.antennapod.core.service.UserAgentInterceptor) Request(okhttp3.Request) BasicAuthorizationInterceptor(de.danoeh.antennapod.core.service.BasicAuthorizationInterceptor) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) Proxy(java.net.Proxy) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) CookieManager(java.net.CookieManager) Cache(okhttp3.Cache) NonNull(androidx.annotation.NonNull)

Example 34 with Credentials

use of okhttp3.Credentials in project AntennaPod by AntennaPod.

the class ProxyDialog method test.

private void test() {
    if (disposable != null) {
        disposable.dispose();
    }
    if (!checkValidity()) {
        setTestRequired(true);
        return;
    }
    TypedArray res = context.getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary });
    int textColorPrimary = res.getColor(0, 0);
    res.recycle();
    String checking = context.getString(R.string.proxy_checking);
    txtvMessage.setTextColor(textColorPrimary);
    txtvMessage.setText("{fa-circle-o-notch spin} " + checking);
    txtvMessage.setVisibility(View.VISIBLE);
    disposable = Completable.create(emitter -> {
        String type = (String) spType.getSelectedItem();
        String host = etHost.getText().toString();
        String port = etPort.getText().toString();
        String username = etUsername.getText().toString();
        String password = etPassword.getText().toString();
        int portValue = 8080;
        if (!TextUtils.isEmpty(port)) {
            portValue = Integer.parseInt(port);
        }
        SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
        Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase(Locale.US));
        OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).proxy(new Proxy(proxyType, address));
        if (!TextUtils.isEmpty(username)) {
            builder.proxyAuthenticator((route, response) -> {
                String credentials = Credentials.basic(username, password);
                return response.request().newBuilder().header("Proxy-Authorization", credentials).build();
            });
        }
        OkHttpClient client = builder.build();
        Request request = new Request.Builder().url("https://www.example.com").head().build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                emitter.onComplete();
            } else {
                emitter.onError(new IOException(response.message()));
            }
        } catch (IOException e) {
            emitter.onError(e);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(() -> {
        txtvMessage.setTextColor(ContextCompat.getColor(context, R.color.download_success_green));
        String message = String.format("%s %s", "{fa-check}", context.getString(R.string.proxy_test_successful));
        txtvMessage.setText(message);
        setTestRequired(false);
    }, error -> {
        error.printStackTrace();
        txtvMessage.setTextColor(ContextCompat.getColor(context, R.color.download_failed_red));
        String message = String.format("%s %s: %s", "{fa-close}", context.getString(R.string.proxy_test_failed), error.getMessage());
        txtvMessage.setText(message);
        setTestRequired(true);
    });
}
Also used : Context(android.content.Context) AlertDialog(androidx.appcompat.app.AlertDialog) SocketAddress(java.net.SocketAddress) Completable(io.reactivex.Completable) Dialog(android.app.Dialog) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) ArrayList(java.util.ArrayList) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Locale(java.util.Locale) View(android.view.View) Response(okhttp3.Response) Schedulers(io.reactivex.schedulers.Schedulers) AdapterView(android.widget.AdapterView) Build(android.os.Build) ContextCompat(androidx.core.content.ContextCompat) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) R(de.danoeh.antennapod.R) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) List(java.util.List) Disposable(io.reactivex.disposables.Disposable) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Proxy(java.net.Proxy) TypedArray(android.content.res.TypedArray) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 35 with Credentials

use of okhttp3.Credentials in project PokeGOAPI-Java by Grover-c13.

the class FightGymExample method main.

/**
 * Fights gyms in the nearby area.
 */
public static void main(String[] args) {
    OkHttpClient http = new OkHttpClient();
    final PokemonGo api = new PokemonGo(http);
    try {
        // Login and set location
        HashProvider hasher = ExampleConstants.getHashProvider();
        api.login(new PtcCredentialProvider(http, ExampleConstants.LOGIN, ExampleConstants.PASSWORD), hasher);
        api.setLocation(ExampleConstants.LATITUDE, ExampleConstants.LONGITUDE, ExampleConstants.ALTITUDE);
        List<Pokemon> pokemons = api.inventories.pokebank.pokemons;
        // List to put all pokemon that can be used in a gym battle
        List<Pokemon> possiblePokemon = new ArrayList<>();
        for (Pokemon pokemon : pokemons) {
            // Check if pokemon has full health and is not deployed in a gym
            if (pokemon.getDeployedFortId().length() == 0) {
                if (pokemon.getStamina() < pokemon.getMaxStamina()) {
                    healPokemonFull(pokemon);
                    if (!(pokemon.isInjured() || pokemon.isFainted())) {
                        possiblePokemon.add(pokemon);
                    }
                    Thread.sleep(1000);
                } else {
                    possiblePokemon.add(pokemon);
                }
            } else {
                System.out.println(pokemon.getPokemonId() + " already deployed.");
            }
        }
        // Sort by highest CP
        Collections.sort(possiblePokemon, new Comparator<Pokemon>() {

            @Override
            public int compare(Pokemon primary, Pokemon secondary) {
                return Integer.compare(secondary.getCp(), primary.getCp());
            }
        });
        // Pick the top 6 pokemon from the possible list
        final Pokemon[] attackers = new Pokemon[6];
        for (int i = 0; i < 6; i++) {
            attackers[i] = possiblePokemon.get(i);
        }
        // Sort from closest to farthest
        MapObjects mapObjects = api.getMap().mapObjects;
        List<Gym> gyms = new ArrayList<>(mapObjects.gyms);
        Collections.sort(gyms, new Comparator<Gym>() {

            @Override
            public int compare(Gym primary, Gym secondary) {
                double lat = api.latitude;
                double lng = api.longitude;
                double distance1 = MapUtil.distFrom(primary.getLatitude(), primary.getLongitude(), lat, lng);
                double distance2 = MapUtil.distFrom(secondary.getLatitude(), secondary.getLongitude(), lat, lng);
                return Double.compare(distance1, distance2);
            }
        });
        for (Gym gym : gyms) {
            // Check if gym is attackable, and check if it is not owned by your team
            if (gym.isAttackable() && gym.getOwnedByTeam() != api.playerProfile.getPlayerData().getTeam()) {
                // Walk to gym; Documented pathing in TravelToPokestopExample
                Point destination = new Point(gym.getLatitude(), gym.getLongitude());
                Path path = new Path(api.getPoint(), destination, 50.0);
                System.out.println("Traveling to " + destination + " at 50KMPH!");
                path.start(api);
                try {
                    while (!path.complete) {
                        Point point = path.calculateIntermediate(api);
                        api.setLatitude(point.getLatitude());
                        api.setLongitude(point.getLongitude());
                        System.out.println("Time left: " + (int) (path.getTimeLeft(api) / 1000) + " seconds.");
                        Thread.sleep(2000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Beginning battle with gym.");
                // Create battle object
                Battle battle = gym.battle();
                // Start battle
                battle.start(new FightHandler(attackers));
                while (battle.active) {
                    handleAttack(api, battle);
                }
                // Heal all pokemon after battle
                for (Pokemon pokemon : possiblePokemon) {
                    if (pokemon.getStamina() < pokemon.getMaxStamina()) {
                        healPokemonFull(pokemon);
                        Thread.sleep(1000);
                    }
                }
                // If prestige reaches 0, deploy your pokemon
                if (battle.gym.getPoints() <= 0) {
                    Pokemon best = possiblePokemon.get(0);
                    System.out.println("Deploying " + best.getPokemonId() + " to gym.");
                    battle.gym.deployPokemon(best);
                }
            }
        }
    } catch (RequestFailedException | InterruptedException e) {
        // failed to login, invalid credentials, auth issue or server issue.
        Log.e("Main", "Failed to login, captcha or server issue: ", e);
    }
}
Also used : Path(com.pokegoapi.util.path.Path) PtcCredentialProvider(com.pokegoapi.auth.PtcCredentialProvider) OkHttpClient(okhttp3.OkHttpClient) ArrayList(java.util.ArrayList) Point(com.pokegoapi.api.map.Point) MapObjects(com.pokegoapi.api.map.MapObjects) Point(com.pokegoapi.api.map.Point) Battle(com.pokegoapi.api.gym.Battle) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) PokemonGo(com.pokegoapi.api.PokemonGo) HashProvider(com.pokegoapi.util.hash.HashProvider) Gym(com.pokegoapi.api.gym.Gym) Pokemon(com.pokegoapi.api.pokemon.Pokemon)

Aggregations

Request (okhttp3.Request)39 Response (okhttp3.Response)29 OkHttpClient (okhttp3.OkHttpClient)22 IOException (java.io.IOException)20 Test (org.junit.Test)16 HttpUrl (okhttp3.HttpUrl)10 RequestBody (okhttp3.RequestBody)9 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)9 ResponseBody (okhttp3.ResponseBody)8 NonNull (androidx.annotation.NonNull)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)6 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)6 Observable (rx.Observable)6 AuthenticationCacheInterceptor (com.burgstaller.okhttp.AuthenticationCacheInterceptor)5 CachingAuthenticatorDecorator (com.burgstaller.okhttp.CachingAuthenticatorDecorator)5 PokemonGo (com.pokegoapi.api.PokemonGo)5 PtcCredentialProvider (com.pokegoapi.auth.PtcCredentialProvider)5