Исключение SocketTimeoutException, создаваемое при вызове веб-API Spotify (Android + Retrofit) - PullRequest
0 голосов
/ 18 апреля 2019

Я разрабатывал приложение, которое использует API Spotify, чтобы получить песню, воспроизводимую в данный момент пользователем, а затем предоставить рекомендации для конкретной дорожки. Этот проект в основном просто для ознакомления с API, но в последнее время я получаю довольно запутанную ошибку.

Я тестировал свой код десятки раз, и он работал совершенно нормально - я даже смог уверенно создать APK. Однако внезапно кажется, что мой запрос к API Spotify прерывается каждый раз, когда пользователь нажимает кнопку, вызывающую метод setUpSpotify(). Я не получаю ошибку каждый раз (что смущает меня еще больше), но когда я получаю, я получаю SocketTimeoutException. Я не прошел ни одной квоты, и мои ключи остались без изменений. Вот мой код:

Выдержка из Рекомендательной деятельности

public static String user_id;

private ImageView albumCover;
private TextView currentSong, currentArtist;
private ListView recSongs;

public SpotifyService spotify_service;

public Map<String, Object> seed_map;

public ArrayList<Recommendations> allRecs = new ArrayList<>();

private static final String CLIENT_ID = "CLIENT_ID";
private static final String REDIRECT_URI = "REDIRECT_URI";
private SpotifyAppRemote mSpotifyAppRemote;

private Dialog myDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loading_screen_layout);
    myDialog = new Dialog(this);

    setUp(MainActivity.global_auth_response);

    user_id = MainActivity.USER_ID;
}

private class GetRecommendations extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... params) {
        Recommendations rec = spotify_service.getRecommendations(seed_map);
        boolean present = false;
        for(int i = 0; i < allRecs.size(); i++)
        {
            String artist1 = allRecs.get(i).tracks.get(0).artists.get(0).name;
            String artist2 = rec.tracks.get(0).artists.get(0).name;

            String song1 = allRecs.get(i).tracks.get(0).name;
            String song2 = rec.tracks.get(0).name;

            if((artist1 + song1).equals(artist2 + song2)) {
                present = true;
                Log.d("duplicate", allRecs.get(i).tracks.get(0).name);
            }
        }

        if(!present)
            allRecs.add(rec);
        return "goteem";
    }
}

public void setUp(final AuthenticationResponse response)
{
    SpotifyApi api = new SpotifyApi();

    api.setAccessToken(response.getAccessToken());

    final SpotifyService spotify = api.getService();

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request newRequest  = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + response.getAccessToken())
                    .build();
            return chain.proceed(newRequest);
        }
    }).build();

    Retrofit retrofit = new Retrofit.Builder()
            .client(client)
            .baseUrl("https://api.spotify.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    SpotifyPlayerApi spotifyPlayerApi = retrofit.create(SpotifyPlayerApi.class);

    Call<CurrentlyPlaying> call = spotifyPlayerApi.getCurrentlyPlaying();
    call.enqueue(new Callback<CurrentlyPlaying>() {
        @Override
        public void onResponse(Call<CurrentlyPlaying> call, retrofit2.Response<CurrentlyPlaying> response) {
            //Toast.makeText(MainActivity.this, "here-toast", Toast.LENGTH_SHORT).show();
            if(!response.isSuccessful())
            {
                // should probably do something here
                return;
            }

            setContentView(R.layout.activity_recommend);
            currentSong = findViewById(R.id.curr_song);
            currentArtist = findViewById(R.id.curr_artist);
            albumCover = findViewById(R.id.album_art);
            recSongs = findViewById(R.id.recommend_list_view);

            spotify_service = spotify;

            final CurrentlyPlaying currentlyPlaying = response.body();

            try {
                if(currentlyPlaying.getIsPlaying()) {
                    currentSong.setText(currentlyPlaying.getItem().getName());
                    currentArtist.setText(currentlyPlaying.getItem().getArtists().get(0).getName());

                    Glide.with(getApplicationContext()).load(currentlyPlaying.getItem().getAlbum().getImages().get(0).getUrl()).into(albumCover);

                    seed_map = new HashMap<String, Object>() {{
                        put("seed_tracks", currentlyPlaying.getItem().getId());
                    }};

                    try {
                        for (int i = 0; i < 20; i++) {
                            String val = new GetRecommendations().execute().get();
                        }
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                        Log.d("error retrieving recs", e.getMessage());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Log.d("error retrieving recs", e.getMessage());
                    }

                    for (Recommendations r : allRecs) {
                        Log.d("rec", r.tracks.get(0).name);
                    }

                    RecListAdapter adapter = new RecListAdapter(allRecs, getApplicationContext());
                    recSongs.setAdapter(adapter);
                    recSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            newSong(allRecs.get(position).tracks.get(position).id);
                        }
                    });
                } else {
                    setContentView(R.layout.nothing_playing_layout);
                }

            } catch (NullPointerException e) {
                setContentView(R.layout.nothing_playing_layout);
            }
        }

        @Override
        public void onFailure(Call<CurrentlyPlaying> call, Throwable t) {
            Toast.makeText(RecommendActivity.this, "Whoops! Something went wrong. Try again in a little bit.", Toast.LENGTH_SHORT).show();
        }
    });
}

Дайте мне знать, если этого кода недостаточно для диагностики. Любая помощь будет принята с благодарностью.

...