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;
}
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();
}
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;
}
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);
});
}
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);
}
}
Aggregations