Search in sources :

Example 61 with OkHttpClient

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);
    });
}
Also used : Bundle(android.os.Bundle) GridView(android.widget.GridView) ProgressBar(android.widget.ProgressBar) SearchView(android.support.v7.widget.SearchView) ItunesAdapter(de.danoeh.antennapod.adapter.itunes.ItunesAdapter) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Intent(android.content.Intent) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Observable(rx.Observable) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) MenuItemUtils(de.danoeh.antennapod.menuhandler.MenuItemUtils) MenuInflater(android.view.MenuInflater) Locale(java.util.Locale) Menu(android.view.Menu) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Button(android.widget.Button) Response(okhttp3.Response) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Log(android.util.Log) Request(okhttp3.Request) LayoutInflater(android.view.LayoutInflater) R(de.danoeh.antennapod.R) MenuItemCompat(android.support.v4.view.MenuItemCompat) Fragment(android.support.v4.app.Fragment) ClientConfig(de.danoeh.antennapod.core.ClientConfig) IOException(java.io.IOException) ViewGroup(android.view.ViewGroup) URLEncoder(java.net.URLEncoder) List(java.util.List) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) Podcast(de.danoeh.antennapod.adapter.itunes.ItunesAdapter.Podcast) OnlineFeedViewActivity(de.danoeh.antennapod.activity.OnlineFeedViewActivity) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Subscription(rx.Subscription) JSONArray(org.json.JSONArray) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JSONArray(org.json.JSONArray) Podcast(de.danoeh.antennapod.adapter.itunes.ItunesAdapter.Podcast) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List)

Example 62 with OkHttpClient

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);
    });
}
Also used : Context(android.content.Context) SocketAddress(java.net.SocketAddress) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Dialog(android.app.Dialog) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) Observable(rx.Observable) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) MDButton(com.afollestad.materialdialogs.internal.MDButton) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Response(okhttp3.Response) AdapterView(android.widget.AdapterView) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) Subscriber(rx.Subscriber) R(de.danoeh.antennapod.R) ContextCompat(android.support.v4.content.ContextCompat) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) 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) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Subscription(rx.Subscription) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) Proxy(java.net.Proxy) TypedArray(android.content.res.TypedArray) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 63 with OkHttpClient

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);
}
Also used : Inject(javax.inject.Inject) MediaType(com.google.common.net.MediaType) Request(okhttp3.Request) Node(org.graylog2.cluster.Node) OkHttpClient(okhttp3.OkHttpClient) HttpHeaders(com.google.common.net.HttpHeaders) JacksonConverterFactory(retrofit2.converter.jackson.JacksonConverterFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Retrofit(retrofit2.Retrofit) SessionAuthenticator(org.graylog2.security.realm.SessionAuthenticator) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request)

Example 64 with OkHttpClient

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();
}
Also used : ProxySelector(java.net.ProxySelector) Proxy(java.net.Proxy) OkHttpClient(okhttp3.OkHttpClient) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) InetAddress(java.net.InetAddress)

Example 65 with OkHttpClient

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);
    }
}
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) NoSuchItemException(com.pokegoapi.exceptions.NoSuchItemException) RequestFailedException(com.pokegoapi.exceptions.request.RequestFailedException) PokemonGo(com.pokegoapi.api.PokemonGo) Pokestop(com.pokegoapi.api.map.fort.Pokestop) HashProvider(com.pokegoapi.util.hash.HashProvider) NearbyPokemon(com.pokegoapi.api.map.pokemon.NearbyPokemon)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)149 Request (okhttp3.Request)73 Response (okhttp3.Response)61 IOException (java.io.IOException)52 Test (org.junit.Test)35 Call (okhttp3.Call)24 Retrofit (retrofit2.Retrofit)24 Interceptor (okhttp3.Interceptor)19 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)18 MockResponse (okhttp3.mockwebserver.MockResponse)18 File (java.io.File)15 GsonBuilder (com.google.gson.GsonBuilder)12 Provides (dagger.Provides)12 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)12 Gson (com.google.gson.Gson)10 ArrayList (java.util.ArrayList)10 List (java.util.List)10 Cache (okhttp3.Cache)10 Observable (rx.Observable)10 Singleton (javax.inject.Singleton)9