如何在for循环中调用外部API

时间:2018-10-02 05:08:21

标签: java

我尝试使用不同的ID调用API,如以下代码所示。但是它仅在第一次运行和停止时执行。任何人都可以帮助解决该问题吗?

idArray的大小为2。

for (int i = 0; i< idArray.size(); i++){
        String id = idArray.get(i);
        Thread.currentThread().sleep(3000);
        String myURI1 = "https://api.bulksms.com/v1/messages/"+id;
        URL url1 = new URL(myURI1);
        System.out.println(myURI1);
        HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
        request1.setDoOutput(true);
        request1.setRequestProperty("Authorization", "Basic " + authEncoded);
        request1.setRequestMethod("GET");
        request1.setRequestProperty( "Content-Type", "application/json"); 
        BufferedReader in1 = new BufferedReader( new InputStreamReader(request1.getInputStream()));
        String inputLine1;
        StringBuffer response1 = new StringBuffer();
        while ((inputLine1 = in1.readLine()) != null) {
            response1.append(inputLine1);
        }
}

1 个答案:

答案 0 :(得分:0)

我希望您将@hgoebl答案推荐给Single URLConnection to fetch only the first line in java using BufferedReader

“ HttpURLConnection无法重用,但是它可以通过设置标头Connection:keep-alive在内部重用到同一服务器的打开连接。显然,如果您连接到其他服务器,则没有任何意义。 “