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());
        }
    }
}
相关推荐
MOON404☾1 小时前
006.Backdoor后门编写
网络·安全·网络安全·系统安全
ha20428941941 小时前
Linux操作系统学习记录之---TcpSocket
linux·网络·c++·学习
李白你好2 小时前
Burp Suite插件 | 高级HTTP头操作工具
网络·网络协议·http
石像鬼₧魂石3 小时前
22端口(OpenSSH 4.7p1)渗透测试完整复习流程(含实战排错)
大数据·网络·学习·安全·ubuntu
xwj_8655743323 小时前
HTTP协议、接口测试流程、接口测试流程&文档&用例
网络·网络协议·http
RisunJan4 小时前
Linux命令-iptables-restore命令(从文件批量恢复 iptables 防火墙规则)
linux·运维·网络
..过云雨5 小时前
网络计算器实现 - 自定义套接字+序列化+守护进程
网络·网络协议·tcp/ip
hugerat6 小时前
在AI的帮助下,用C++构造微型http server
linux·c++·人工智能·http·嵌入式·嵌入式linux
三两肉6 小时前
HTTPS ECDHE 握手全解析
网络协议·https·github·rsa·echde
小宇的天下6 小时前
HBM(高带宽内存)深度解析:先进封装视角的技术指南
网络·人工智能