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());
        }
    }
}
相关推荐
whoarethenext2 分钟前
c网络库libevent的http常用函数的使用(附带源码)
网络·c++·http·libevent
尘世中迷途小码农20 分钟前
使用O_DIRECT + 批量写数据到磁盘对丢包率的优化
网络
hellojackjiang201123 分钟前
全平台开源即时通讯IM框架MobileIMSDK:7端+TCP/UDP/WebSocket协议,鸿蒙NEXT端已发布,5.7K Stars
网络·harmonyos·即时通讯·im开发
HeLLo_a1192 小时前
第11章 安全网络架构和组件(一)
linux·服务器·网络
薯条不要番茄酱2 小时前
【网络原理】从零开始深入理解HTTP的报文格式(一)
网络·网络协议·http
南川琼语2 小时前
TCP概念+模拟tcp服务器及客户端
linux·服务器·网络·tcp/ip
智联视频超融合平台3 小时前
慧港口新纪元:视频监控联网平台赋能高效安全运营
网络·网络协议·音视频·实时音视频·视频编解码
一只很酸de橘子6 小时前
关于https请求丢字符串导致收到报文解密失败问题
网络协议·http·https
潘yi.7 小时前
web技术与nginx网站环境部署
服务器·网络·nginx
Jtti8 小时前
Jtti:nginx服务器如何限制访问频率
服务器·网络·nginx