gpt4 book ai didi

java - 来自 Java 应用程序的 GET 请求期间收到 403 错误

转载 作者:行者123 更新时间:2023-12-02 09:07:11 25 4
gpt4 key购买 nike

我尝试使用 RestTemplate 库通过 JAVA 客户端执行 GET 请求,导致以下错误:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden

当我尝试通过命令行访问相同的 URL 时,它工作正常。在此处发布 cURL 命令和 Java 代码片段。

cURL:

curl -X GET -H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json" https://xxxx-xxxx-xxxx {"key":"value"}

JAVA 片段:

String URL="https://xyz";
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();

//setting up the required headers
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("Authorization", "Bearer "+accessToken);

HttpEntity<String> entity = new HttpEntity<String>("body",headers);

//get request
ResponseEntity<String> responseEntity = restTemplate.exchange(URL, HttpMethod.GET, entity, String.class);

P.S - 问题是否是因为 URL 是 HTTPS 而不是 HTTP 所致?

最佳答案

添加用户代理 header ,尝试让我们知道它是否有效。

String URL="https://xyz";
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();

//setting up the required headers
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
//settting user agent
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");

headers.set("Authorization", "Bearer "+accessToken);

HttpEntity<String> entity = new HttpEntity<String>("body",headers);

//get request
ResponseEntity<String> responseEntity = restTemplate.exchange(URL, HttpMethod.GET, entity, String.class);

关于java - 来自 Java 应用程序的 GET 请求期间收到 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59715265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com