如何使用HttpURLConnection处理Error请求呢?
下文笔者讲述使用HttpURLConnection捕捉Error请求的方法分享,如下所示
定义后台spring mvc返回错误状态码页面
实现思路:
通过responseCode的返回状态码判断
然后使用connection.getErrorStream()
例:
定义后台spring mvc返回错误状态码页面
@GetMapping("/error")
public ResponseEntity error() {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("error");
}
HttpURLConnnection捕捉Error请求页面
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/error").openConnection();
connection.setRequestMethod("GET");
//write header
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
BufferedReader reader;
try {
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
log.error("发生异常,code={}", responseCode);
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} finally {
connection.disconnect();
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


