http 请求返回307

错误的原因

发现发生临时重定向的原因是我在具体的 url 后面少加了一个 /

  1. /xxx 这个发生了临时重定向请求
  2. /xxx/ 这个请求不会
    可能是因为我请求的服务器对最终请求是否添加 / 有特殊的处理,在开发中,最好由对接方实际的url请求值
    HTTP 状态码 307 Temporary Redirect 是一种临时重定向,表示客户端应该使用相同的 HTTP 方法重新发送请求到指定的新位置。

解决方案

Hutool 的 HTTP 请求工具类处理 307

可以通过设置 HttpRequest 的 setFollowRedirects 来自动处理重定向。

java 复制代码
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class HttpUtilExample {
    public static void main(String[] args) {
        String url = "http://example.com"; // 替换为实际的URL

        // 发送请求,并自动跟随重定向
        HttpResponse response = HttpRequest.get(url)
                .setFollowRedirects(true) // 开启自动重定向
                .execute();

        System.out.println(response.body());
    }
}

如何手动处理重定向

可以通过读取响应头中的 Location 字段来获取新的 URL,并重新发起请求

java 复制代码
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class HttpUtilExample {
    public static void main(String[] args) {
        String url = "http://example.com"; // 原始URL

        HttpResponse response = HttpRequest.get(url)
                .setFollowRedirects(false) // 手动处理重定向
                .execute();

        if (response.getStatus() == 307) {
            // 获取重定向的URL
            String redirectUrl = response.header("Location");

            // 重新请求重定向的URL
            HttpResponse redirectResponse = HttpRequest.get(redirectUrl)
                    .execute();

            System.out.println(redirectResponse.body());
        } else {
            System.out.println(response.body());
        }
    }
}
相关推荐
没有bug.的程序员15 小时前
Service Mesh 下的流量治理:灰度、熔断、限流的深度实践与代价剖析
网络·云原生·限流·熔断·灰度发布·流量治理·servicemesh
禾叙_15 小时前
【netty】Netty之TCP链接
网络·网络协议·tcp/ip
星马梦缘15 小时前
计算机网络期末焚决 2024级
网络·计算机网络·dns·ospf·流量控制·路由算法·拥塞控制
zhengfei61115 小时前
【Slack 安全工具箱】—— 多维度一体化安全管理平台
网络·安全·web安全
qq_4017004115 小时前
什么是网关?
网络
半路_出家ren15 小时前
17.python爬虫基础,基于正则表达式的爬虫,基于BeautifulSoup的爬虫
网络·爬虫·python·网络协议·正则表达式·网络爬虫·beautifulsoup
栗子叶15 小时前
SSE、长轮询与 WebSocket 连接资源对比及 Spring Boot 配置指南
spring boot·websocket·网络协议
呉師傅15 小时前
国产麒麟系统卡启动项或图标如何解决
运维·网络·windows·计算机外设·电脑
徐子童16 小时前
网络协议---TCP协议
网络·网络协议·tcp/ip·面试题·1024程序员节
ikkkkkkkl16 小时前
计算机网络:应用层
网络·计算机网络·应用层