如何使用HttpURLConnection处理redirect请求呢?

书欣 Java经验 发布时间:2022-10-13 10:13:51 阅读数:17597 1 HttpURLConnection
下文笔者讲述使用HttpURLConnection处理Redirect请求的方法分享,如下所示
实现思路:
    通过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();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202210/16656276664627.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者