欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > http 请求返回307

http 请求返回307

2024/10/26 6:12:35 来源:https://blog.csdn.net/xiaomzhng/article/details/143225823  浏览:    关键词:http 请求返回307

错误的原因

发现发生临时重定向的原因是我在具体的 url 后面少加了一个 /

  1. /xxx 这个发生了临时重定向请求
  2. /xxx/ 这个请求不会
    可能是因为我请求的服务器对最终请求是否添加 / 有特殊的处理,在开发中,最好由对接方实际的url请求值

HTTP 状态码 307 Temporary Redirect 是一种临时重定向,表示客户端应该使用相同的 HTTP 方法重新发送请求到指定的新位置。

解决方案

Hutool 的 HTTP 请求工具类处理 307

可以通过设置 HttpRequest 的 setFollowRedirects 来自动处理重定向。

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,并重新发起请求

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;public class HttpUtilExample {public static void main(String[] args) {String url = "http://example.com"; // 原始URLHttpResponse response = HttpRequest.get(url).setFollowRedirects(false) // 手动处理重定向.execute();if (response.getStatus() == 307) {// 获取重定向的URLString redirectUrl = response.header("Location");// 重新请求重定向的URLHttpResponse redirectResponse = HttpRequest.get(redirectUrl).execute();System.out.println(redirectResponse.body());} else {System.out.println(response.body());}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com