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());
        }
    }
}
相关推荐
robur16 分钟前
H3C V7路由器升级软件时提示无足够存储空间
网络·路由器·升级·h3c
云飞云共享云桌面28 分钟前
研发部门使用SolidWorks,三维设计云桌面应该怎么选?
运维·服务器·前端·网络·自动化·电脑
MicroTech202530 分钟前
微算法科技(NASDAQ:MLGO)优化区块链身份证明(PoI)技术:构建可信网络的基石
网络·科技·区块链
honsor1 小时前
一种采用POE供电的RJ45网络型温湿度传感器
运维·服务器·网络
Tandy12356_1 小时前
手写TCP/IP协议栈——数据包结构定义
c语言·网络·c++·计算机网络
繁华似锦respect1 小时前
HTTPS 中 TLS 协议详细过程 + 数字证书/签名深度解析
开发语言·c++·网络协议·http·单例模式·设计模式·https
Tandy12356_1 小时前
手写TCP/IP协议栈——环境配置
服务器·网络·网络协议·tcp/ip
老蒋新思维1 小时前
创客匠人洞察:创始人 IP 变现的长期主义,文化根基与 AI 杠杆的双重赋能
大数据·网络·人工智能·tcp/ip·重构·创始人ip·创客匠人
clear sky .1 小时前
TCP,UDP使用socket编程流程
网络协议·tcp/ip·udp
I · T · LUCKYBOOM2 小时前
21.Linux网络设置
linux·运维·网络