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());
        }
    }
}
相关推荐
acrel77 分钟前
医院用电隐患治理与节能降耗及智慧能源平台应用
网络·数据库
Escalating_xu1 小时前
【Linux 网络编程】应用层协议 HTTP(下):Header、连接管理与 C++ HTTP 服务器
linux·服务器·网络
明天也要努力学习2 小时前
TCP 协议的相关特性
网络·网络协议·tcp/ip
SHENGWEI胜为3 小时前
局域网出现 IP 地址冲突怎么办?如何从 ARP 表定位故障设备
网络协议·tcp/ip·php
qq_401700413 小时前
100 个 IoT 小项目,给 ESP32 入门补上实操
前端·网络·stm32
2401_873479403 小时前
源IP告警太多用什么工具分层?ASN与风险评分操作指南
网络·网络协议·tcp/ip
见闻小天地3 小时前
新手入门:印刷包装设备的伺服和PLC运动控制方案各管什么?七步选型讲清楚
运维·网络·数据库·人工智能
father_12274 小时前
Greenplum 集群故障恢复与主备同步机制实战
linux·网络·greenplum
中电金信5 小时前
开发更高效、监控更实时、运维更省心,源启数据开发平台构筑一站式数据开发新底座
网络·数据库·人工智能