use of okhttp3.OkHttpClient in project AntennaPod by AntennaPod.
the class ItunesSearchFragment method search.
private void search(String query) {
if (subscription != null) {
subscription.unsubscribe();
}
gridView.setVisibility(View.GONE);
txtvError.setVisibility(View.GONE);
butRetry.setVisibility(View.GONE);
txtvEmpty.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
subscription = rx.Observable.create((Observable.OnSubscribe<List<Podcast>>) subscriber -> {
String encodedQuery = null;
try {
encodedQuery = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
if (encodedQuery == null) {
encodedQuery = query;
}
String formattedUrl = String.format(API_URL, query).replace(' ', '+');
OkHttpClient client = AntennapodHttpClient.getHttpClient();
Request.Builder httpReq = new Request.Builder().url(formattedUrl).header("User-Agent", ClientConfig.USER_AGENT);
List<Podcast> podcasts = new ArrayList<>();
try {
Response response = client.newCall(httpReq.build()).execute();
if (response.isSuccessful()) {
String resultString = response.body().string();
JSONObject result = new JSONObject(resultString);
JSONArray j = result.getJSONArray("results");
for (int i = 0; i < j.length(); i++) {
JSONObject podcastJson = j.getJSONObject(i);
Podcast podcast = Podcast.fromSearch(podcastJson);
podcasts.add(podcast);
}
} else {
String prefix = getString(R.string.error_msg_prefix);
subscriber.onError(new IOException(prefix + response));
}
} catch (IOException | JSONException e) {
subscriber.onError(e);
}
subscriber.onNext(podcasts);
subscriber.onCompleted();
}).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(podcasts -> {
progressBar.setVisibility(View.GONE);
updateData(podcasts);
}, error -> {
Log.e(TAG, Log.getStackTraceString(error));
progressBar.setVisibility(View.GONE);
txtvError.setText(error.toString());
txtvError.setVisibility(View.VISIBLE);
butRetry.setOnClickListener(v -> search(query));
butRetry.setVisibility(View.VISIBLE);
});
}
use of okhttp3.OkHttpClient in project AntennaPod by AntennaPod.
the class ProxyDialog method test.
private void test() {
if (subscription != null) {
subscription.unsubscribe();
}
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);
subscription = Observable.create(new Observable.OnSubscribe<Response>() {
@Override
public void call(Subscriber<? super Response> subscriber) {
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.valueOf(port);
}
SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
Proxy proxy = new Proxy(proxyType, address);
OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).proxy(proxy);
builder.interceptors().clear();
OkHttpClient client = builder.build();
if (!TextUtils.isEmpty(username)) {
String credentials = Credentials.basic(username, password);
client.interceptors().add(chain -> {
Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
return chain.proceed(request);
});
}
Request request = new Request.Builder().url("http://www.google.com").head().build();
try {
Response response = client.newCall(request).execute();
subscriber.onNext(response);
} catch (IOException e) {
subscriber.onError(e);
}
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(response -> {
int colorId;
String icon;
String result;
if (response.isSuccessful()) {
colorId = R.color.download_success_green;
icon = "{fa-check}";
result = context.getString(R.string.proxy_test_successful);
} else {
colorId = R.color.download_failed_red;
icon = "{fa-close}";
result = context.getString(R.string.proxy_test_failed);
}
int color = ContextCompat.getColor(context, colorId);
txtvMessage.setTextColor(color);
String message = String.format("%s %s: %s", icon, result, response.message());
txtvMessage.setText(message);
setTestRequired(!response.isSuccessful());
}, error -> {
String icon = "{fa-close}";
String result = context.getString(R.string.proxy_test_failed);
int color = ContextCompat.getColor(context, R.color.download_failed_red);
txtvMessage.setTextColor(color);
String message = String.format("%s %s: %s", icon, result, error.getMessage());
txtvMessage.setText(message);
setTestRequired(true);
});
}
use of okhttp3.OkHttpClient in project graylog2-server by Graylog2.
the class RemoteInterfaceProvider method get.
public <T> T get(Node node, final String authorizationToken, Class<T> interfaceClass) {
final OkHttpClient okHttpClient = this.okHttpClient.newBuilder().addInterceptor(chain -> {
final Request original = chain.request();
Request.Builder builder = original.newBuilder().header(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString()).method(original.method(), original.body());
if (authorizationToken != null) {
builder = builder.header(HttpHeaders.AUTHORIZATION, authorizationToken).header(SessionAuthenticator.X_GRAYLOG_NO_SESSION_EXTENSION, "true");
}
return chain.proceed(builder.build());
}).build();
final Retrofit retrofit = new Retrofit.Builder().baseUrl(node.getTransportAddress()).addConverterFactory(JacksonConverterFactory.create(objectMapper)).client(okHttpClient).build();
return retrofit.create(interfaceClass);
}
use of okhttp3.OkHttpClient in project graylog2-server by Graylog2.
the class OkHttpClientProvider method get.
@Override
public OkHttpClient get() {
final OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().retryOnConnectionFailure(true).connectTimeout(connectTimeout.getQuantity(), connectTimeout.getUnit()).writeTimeout(writeTimeout.getQuantity(), writeTimeout.getUnit()).readTimeout(readTimeout.getQuantity(), readTimeout.getUnit());
if (httpProxyUri != null) {
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyUri.getHost(), httpProxyUri.getPort()));
final ProxySelector proxySelector = new ProxySelector() {
@Override
public List<Proxy> select(URI uri) {
try {
final InetAddress targetAddress = InetAddress.getByName(uri.getHost());
if (targetAddress.isLoopbackAddress()) {
return ImmutableList.of(Proxy.NO_PROXY);
}
} catch (UnknownHostException e) {
LOG.debug("Unable to resolve host name for proxy selection: ", e);
}
return ImmutableList.of(proxy);
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
LOG.warn("Unable to connect to proxy: ", ioe);
}
};
clientBuilder.proxySelector(proxySelector);
}
return clientBuilder.build();
}
use of okhttp3.OkHttpClient in project PokeGOAPI-Java by Grover-c13.
the class CatchPokemonAtAreaExample method main.
/**
* Catches a pokemon at an area.
*
* @param args args
*/
public static void main(String[] args) {
OkHttpClient http = new OkHttpClient();
final PokemonGo api = new PokemonGo(http);
try {
HashProvider hasher = ExampleConstants.getHashProvider();
api.login(new PtcCredentialProvider(http, ExampleConstants.LOGIN, ExampleConstants.PASSWORD), hasher);
api.setLocation(ExampleConstants.LATITUDE, ExampleConstants.LONGITUDE, ExampleConstants.ALTITUDE);
// Catch all pokemon in the current area
catchArea(api);
MapObjects mapObjects = api.getMap().getMapObjects();
//Find all pokestops with pokemon nearby
List<Pokestop> travelPokestops = new ArrayList<>();
Set<NearbyPokemon> nearby = mapObjects.getNearby();
for (NearbyPokemon nearbyPokemon : nearby) {
String fortId = nearbyPokemon.getFortId();
//Check if nearby pokemon is near a pokestop
if (fortId != null && fortId.length() > 0) {
//Find the pokestop with the fort id of the nearby pokemon
Pokestop pokestop = mapObjects.getPokestop(fortId);
if (pokestop != null && !travelPokestops.contains(pokestop)) {
travelPokestops.add(pokestop);
}
}
}
//Sort from closest to farthest
Collections.sort(travelPokestops, new Comparator<Pokestop>() {
@Override
public int compare(Pokestop primary, Pokestop secondary) {
double lat = api.getLatitude();
double lng = api.getLongitude();
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 (Pokestop pokestop : travelPokestops) {
Point destination = new Point(pokestop.getLatitude(), pokestop.getLongitude());
//Use the current player position as the source and the pokestop position as the destination
//Travel to Pokestop at 20KMPH
Path path = new Path(api.getPoint(), destination, 20.0);
System.out.println("Traveling to " + destination + " at 20KMPH!");
path.start(api);
try {
while (!path.isComplete()) {
//Calculate the desired intermediate point for the current time
Point point = path.calculateIntermediate(api);
//Set the API location to that point
api.setLatitude(point.getLatitude());
api.setLongitude(point.getLongitude());
//Sleep for 2 seconds before setting the location again
Thread.sleep(2000);
}
} catch (InterruptedException e) {
break;
}
System.out.println("Finished traveling to pokestop, catching pokemon.");
catchArea(api);
}
} catch (NoSuchItemException | RequestFailedException e) {
Log.e("Main", "An exception occurred while running example: ", e);
}
}
Aggregations