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());
        }
    }
}
相关推荐
Tadas-Gao13 分钟前
TCP粘包现象的深度解析:从协议本质到工程实践
网络·网络协议·云原生·架构·tcp
IOsetting35 分钟前
金山云主机添加开机路由
运维·服务器·开发语言·网络·php
XiaoMu_0011 小时前
自动化漏洞扫描与预警平台
运维·网络·自动化
崎岖Qiu1 小时前
【计算机网络 | 第九篇】PPP:点对点协议
网络·笔记·计算机网络·ppp
23zhgjx-zgx1 小时前
USB 设备通信数据包审计与键值解析报告
网络·ctf·流量
WJ.Polar1 小时前
FTP、Telnet、PPP、SNMP协议
服务器·网络
BLSxiaopanlaile1 小时前
《凤凰架构-构建可靠的大型分布式系统》读书笔记 -关于网络通信安全性的一些总结
http·加密·认证授权·网络通信安全
aesthetician1 小时前
实时通信的艺术:Server-Sent Events (SSE) 与 WebSocket 的深度解析
网络·websocket·网络协议
REDcker2 小时前
gRPC完整文档
服务器·网络·c++·网络协议·grpc
..过云雨2 小时前
多路转接select系统调用详解
网络·网络协议·tcp/ip