阅读量:0
在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块中打印错误消息并打印异常堆栈跟踪。您可以根据您的需求添加更多的异常处理代码,比如记录错误日志,返回特定的错误信息给客户端等。