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());
        }
    }
}
相关推荐
网络小江8 小时前
上网第三十九课:TCP 的可靠性——滑动窗口、重传与拥塞控制
网络协议
国科安芯9 小时前
一颗当两颗用:ASC4T245S 的“两组独立 2 位 + 控制挂靠 VCCA“账
网络·电平转换·抗辐射·在轨服务
冯胤清9 小时前
《Jev-IDS:网络入侵检测一种系统模型》论文深度分析总结
网络
91刘仁德10 小时前
HTTP协议详解:从URL到HTTP服务器的完整实战
服务器·网络·笔记·网络协议·http
Sarapines Programmer10 小时前
【Wireshark】安装与使用指南
网络·测试工具·wireshark
可乐鸡翅yeah_12 小时前
hls.js 手动自定义 http 请求 loader,修改请求头实战
开发语言·前端·javascript·网络协议·http·ecmascript·m3u8在线
星夜夏空9912 小时前
网络编程(5)—— Reactor实现(v4)
网络
pt104314 小时前
CML网络仿真入门-2:使用CML模拟网络实验环境
运维·网络协议
rest102415 小时前
用io_uring进行io测试
网络
恒拓高科WorkPlus15 小时前
企业怎样选择IM即时通讯平台?私有化部署还是SaaS更适合?
网络·github