如何使用Java进行HTTP请求并处理响应错误
在Java中,我们可以使用HttpURLConnection或者HttpClient来发送HTTP请求。下面是一个使用HttpURLConnection的例子:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
// 创建URL对象
URL url = new URL("http://example.com");
// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法(GET或POST等)
connection.setRequestMethod("GET");
// 获取响应状态码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 处理响应数据
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null)) {
content.append(inputLine);
}
in.close();
System.out.println("Response Content: " + content.toString());
} else {
System.out.println("Failed to retrieve data. Response Code: " + responseCode);
}
}
}
这个例子中,我们发送了一个GET请求到指定的URL。然后处理了响应的状态码,并根据状态码来决定是否打印响应内容以及如何处理错误。
还没有评论,来说两句吧...