java - 如何减慢 API 请求速度?

标签 java android api httphandler themoviedb-api

我正在使用 makeServiceCall 从 TheMovieDB API 获取 JSON 数据。

由于他们没有电影 ID 列表,我必须循环遍历 ID。

String JSONString = httpHandler.makeServiceCall("https://api.themoviedb.org/3/movie/" + 
                                       i + 
                                       "?api_key=" + API_KEY);

我=id

API_KEY = 我的 API key 。

当我循环访问 URL 时,我收到一些调用的 IOException。

I/System.out: ID:   152
I/System.out: ID:   160
I/System.out: ID:   165
I/System.out: ID:   168
I/System.out: ID:   171
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/181?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/184?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/185?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/186?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/187?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/188?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/189?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/190?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/191?api_key=b692b9da86f1cf0c1b623ea6e2770101
E/HttpHandler: IOException: https://api.themoviedb.org/3/movie/192?api_key=b692b9da86f1cf0c1b623ea6e2770101

一些 IOException 只是返回为 null 的 URL,如

{"status_code":34,"status_message":"The resource you requested could not be found."}

如何减慢 for 循环速度,使其不超过 API 调用限制?

HttpHandler:

package com.example.zdroa.yplex;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpHandler {
    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }
    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

我的调用是在 AsyncTask 内部进行的

class getWorkingIdsFromAPI extends AsyncTask<Void, Void, Void> {

    ArrayList<String> alPersonType;

    public getWorkingIdsFromAPI(ArrayList<String> arrayList) {
        alPersonType = new ArrayList<>(arrayList);
    }

    @Override
    protected Void doInBackground(Void... params) {

        final HttpHandler httpHandler = new HttpHandler();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           @Override
                           public void run() {
                               for (int i = 0; i < 200; i++) { //20000
                                   String JSONString = httpHandler.makeServiceCall("https://api.themoviedb.org/3/movie/" + i + "?api_key=" + API_KEY);

                                   if (JSONString != null) {
                                       try {
                                           JSONObject jsonObject = new JSONObject(JSONString);
                                           JSONArray jsonArray = jsonObject.getJSONArray("genres");

                                           boolean cont = true;

                                           for (int a = 0; a < jsonArray.length(); a++) {

                                               JSONObject jsonObject1 = jsonArray.getJSONObject(a);
                                               String string = jsonObject1.getString("name");

                                               for (int b = 0; b < alPersonType.size(); b++) {
                                                   if (string.equals(alPersonType.get(b))) {
                                                       cont = false;
                                                   }
                                               }
                                           }

                                           if (cont) {
                                               String id = String.valueOf(jsonObject.getInt("id"));
                                               System.out.println("ID:   " + id);

                                               switch (id.length()) {
                                                   case 1:
                                                       id = "0000" + id;
                                                       break;
                                                   case 2:
                                                       id = "000" + id;
                                                       break;
                                                   case 3:
                                                       id = "00" + id;
                                                       break;
                                                   case 4:
                                                       id = "0" + id;
                                                       break;
                                               }
                                               switch (i) {
                                                   case 1:
                                                       STRING_LIST_OF_IDS = STRING_LIST_OF_IDS + id;
                                                       break;
                                                   default:
                                                       STRING_LIST_OF_IDS = ", " + STRING_LIST_OF_IDS + id;
                                                       break;
                                               }
                                           }

                                       } catch (JSONException e) {
                                           e.printStackTrace();
                                       }
                                   }
                               }
                           }
                       }

                , 3000);


        return null;
    }


    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        //add STRING_LIST_OF_IDS
        getStringOfIdsFromDB();
    }
}

最佳答案

您做错了,因为计时器任务将在每 3000 毫秒后重复一次,它将执行循环中的所有请求。你可以像这样改变你的代码。

 ArrayList<String> alPersonType;
  i=0; // initialise your variable once instead of each time in task

public getWorkingIdsFromAPI(ArrayList<String> arrayList) {
    alPersonType = new ArrayList<>(arrayList);
}
@Override
protected Void doInBackground(Void... params) {


    final HttpHandler httpHandler = new HttpHandler();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                           if(i < 200) { String JSONString = httpHandler.makeServiceCall("https://api.themoviedb.org/3/movie/" + i + "?api_key=" + API_KEY);

                               if (JSONString != null) {
                                   try {
                                       JSONObject jsonObject = new JSONObject(JSONString);
                                       JSONArray jsonArray = jsonObject.getJSONArray("genres");

                                       boolean cont = true;

                                       for (int a = 0; a < jsonArray.length(); a++) {

                                           JSONObject jsonObject1 = jsonArray.getJSONObject(a);
                                           String string = jsonObject1.getString("name");

                                           for (int b = 0; b < alPersonType.size(); b++) {
                                               if (string.equals(alPersonType.get(b))) {
                                                   cont = false;
                                               }
                                           }
                                       }

                                       if (cont) {
                                           String id = String.valueOf(jsonObject.getInt("id"));
                                           System.out.println("ID:   " + id);

                                           switch (id.length()) {
                                               case 1:
                                                   id = "0000" + id;
                                                   break;
                                               case 2:
                                                   id = "000" + id;
                                                   break;
                                               case 3:
                                                   id = "00" + id;
                                                   break;
                                               case 4:
                                                   id = "0" + id;
                                                   break;
                                           }
                                           switch (i) {
                                               case 1:
                                                   STRING_LIST_OF_IDS = STRING_LIST_OF_IDS + id;
                                                   break;
                                               default:
                                                   STRING_LIST_OF_IDS = ", " + STRING_LIST_OF_IDS + id;
                                                   break;
                                           }
                                       }

                                   } catch (JSONException e) {
                                       e.printStackTrace();
                                   }i++;//increase the counter 
                               }
                           }
                       }
                   }

            , 3000);return null;
}

您还可以使用 Thread.sleep() 采用不同的方法来更改您的 doin 背景,如下所示

@Override
protected Void doInBackground(Void... params) {

    final HttpHandler httpHandler = new HttpHandler();

                           for (int i = 0; i < 200; i++) {try {
Thread.sleep(400);} catch (InterruptedException e) {
e.printStackTrace();} 
                              String JSONString = httpHandler.makeServiceCall("https://api.themoviedb.org/3/movie/" + i + "?api_key=" + API_KEY);

                               if (JSONString != null) {
                                   try {
                                       JSONObject jsonObject = new JSONObject(JSONString);
                                       JSONArray jsonArray = jsonObject.getJSONArray("genres");

                                       boolean cont = true;

                                       for (int a = 0; a < jsonArray.length(); a++) {

                                           JSONObject jsonObject1 = jsonArray.getJSONObject(a);
                                           String string = jsonObject1.getString("name");

                                           for (int b = 0; b < alPersonType.size(); b++) {
                                               if (string.equals(alPersonType.get(b))) {
                                                   cont = false;
                                               }
                                           }
                                       }

                                       if (cont) {
                                           String id = String.valueOf(jsonObject.getInt("id"));
                                           System.out.println("ID:   " + id);

                                           switch (id.length()) {
                                               case 1:
                                                   id = "0000" + id;
                                                   break;
                                               case 2:
                                                   id = "000" + id;
                                                   break;
                                               case 3:
                                                   id = "00" + id;
                                                   break;
                                               case 4:
                                                   id = "0" + id;
                                                   break;
                                           }
                                           switch (i) {
                                               case 1:
                                                   STRING_LIST_OF_IDS = STRING_LIST_OF_IDS + id;
                                                   break;
                                               default:
                                                   STRING_LIST_OF_IDS = ", " + STRING_LIST_OF_IDS + id;
                                                   break;
                                           }
                                       }

                                   } catch (JSONException e) {
                                       e.printStackTrace();
                                   }
                               }
                           }
                    ;


    return null;
}

关于java - 如何减慢 API 请求速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44037732/

相关文章:

java - 扩展泛型、传递类型的泛型

android - 静默安装其他apk

api - Paypal API退款

javascript - 如何将这段代码打印成 HTML?

java - 使用 Spring 集成从服务器向客户端发送请求

java - 单击按钮时从 SQLite 数据库获取下一条记录

java定时器不递增

android - 如何从蓝牙接收字节数组并将字节数组作为图像文件保存到SD卡

android - 将两个适配器设置到同一个列表

python - Google Calendar API 日期时间格式 python