Java中使用数组通过HTTP GET获取多个URL的方法可以通过以下步骤来实现:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
String[] urls = {"https://example.com/url1", "https://example.com/url2", "https://example.com/url3"};
for (String urlStr : urls) {
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println("Response from " + urlStr + ": " + response.toString());
} else {
System.out.println("Failed to get response from " + urlStr + ". Response code: " + responseCode);
}
connection.disconnect();
} catch (Exception e) {
System.out.println("Error while sending HTTP GET request to " + urlStr + ": " + e.getMessage());
}
}
上述代码中,我们首先通过URL类创建URL对象,然后打开连接并设置请求方法为GET。接着,我们检查响应码是否为HTTP_OK(200),如果是则读取响应数据,并在控制台打印出来。如果响应码不是200,则打印出失败的信息。最后,记得关闭连接。
对于这个问题的回答中,没有提到云计算相关的名词。如果要推荐腾讯云相关产品,可以根据具体需求来选择适合的产品,比如腾讯云函数(SCF)可以用于处理HTTP请求,腾讯云对象存储(COS)可以用于存储获取到的数据等。具体产品推荐可以参考腾讯云官网的相关页面。
请注意,以上答案仅供参考,实际情况应根据具体需求和环境进行调整。
领取专属 10元无门槛券
手把手带您无忧上云