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());
        }
    }
}
相关推荐
LabVIEW开发6 小时前
ALMEMO 采集器 + LabVIEW 多路温度怎么采?
网络·labview
郝学胜-神的一滴11 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
王亚博_Abel13 小时前
域名是怎么变成 IP 的?手拆 DNS 解析四个实验实测
网络·网络协议·tcp/ip
用户849137175471613 小时前
两版 SNMP 报文只差 1 个字节,我盯了半天才看懂问题出在哪
网络协议
AndreaYYmm14 小时前
SIGUSR2 触发热重载:一个正在抓包的进程如何原子地换掉规则集
c语言·网络协议
Thanks_ks14 小时前
RESTful API 到底是什么:从 URL 设计讲到请求方法的选择
spring boot·http·状态码·url·幂等性·restful api·无状态
用户849137175471619 小时前
为什么 SNMP 叫"简单"?真相是:设备少干活,复杂全甩给了你
网络协议
always202219 小时前
AI运行时 · 11 - Serverless API 网关:冷启动、流量路由、Autoscaler、函数生命周期
网络·人工智能·serverless
白小飞不会飞20 小时前
【AUTOSAR】CP SOME/IP-TP
c++·嵌入式硬件·网络协议·车载系统·autosar
神一样的老师20 小时前
用 FCU1501 双网口打通两个不同网段:IP 转发 + NAT 实战
网络·网络协议·tcp/ip