在Java中處理GET請求的異常可以使用try-catch語句來捕獲和處理異常。以下是一個簡單的示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequest {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
在上面的示例中,我們使用try-catch語句來捕獲任何可能發生的異常,然后在catch塊中打印錯誤消息并打印異常堆棧跟蹤。您可以根據您的需求添加更多的異常處理代碼,比如記錄錯誤日志,返回特定的錯誤信息給客戶端等。