如何使用HttpURLConnection处理redirect请求呢?
下文笔者讲述使用HttpURLConnection处理Redirect请求的方法分享,如下所示
定义后台spring mvc返回跳转状态码页面
实现思路:
通过responseCode的返回状态码进行判断是否需要跳转
例:
定义后台spring mvc返回跳转状态码页面
@GetMapping("/redirect")
public ResponseEntity redirect() {
return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, "http://www.java265.com").build();
}
HttpURLConnnection捕捉Redirect请求页面
HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/redirect").openConnection();
connection.setRequestMethod("GET");
//写头文件
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
//取消自动重定向
connection.setInstanceFollowRedirects(false);
int responseCode = connection.getResponseCode();
log.info("response code : {}", responseCode);
if (responseCode == 302) {
String location = connection.getHeaderField("Location");
URLConnection redirect = new URL(location).openConnection();
redirect.connect();
// read response
try (BufferedReader reader = new BufferedReader(new InputStreamReader(redirect.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} finally {
connection.disconnect();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


