Java API调用异常处理:HttpURLConnection连接失败示例
在Java中,当我们使用HttpURLConnection进行API调用时,可能会遇到连接失败的情况。下面是一个具体的异常处理示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ApiCallExceptionExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://api.example.com/data");
// 使用HttpURLConnection建立连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法(这里是GET)
connection.setRequestMethod("GET");
// 检查响应状态码(404表示未找到资源)
int responseCode = connection.getResponseCode();
if (responseCode == 404) {
System.out.println("API Call Failed: Resource Not Found");
return;
}
// 获取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())));
// 处理和打印响应内容
String inputLine;
StringBuffer responseContent = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseContent.append(inputLine);
}
System.out.println("API Call Response: " + responseContent.toString());
} catch (Exception e) {
// 连接失败或其他异常时,捕获并打印异常信息
System.out.println("API Call Exception: " + e.getMessage());
}
}
}
这段代码首先创建一个URL对象,并使用HttpURLConnection建立连接。如果请求成功(响应状态码为200),则会打印出API调用的响应内容。如果出现任何连接失败或其他异常,也会捕获并打印出具体的异常信息。
还没有评论,来说两句吧...