我正在尝试向 Genius API 提出请求,但我在使用 OkHTTP 时遇到了一些问题。这是我用来调用电话的小脚本:
public class OkHttpScript {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.header("Authorization", "Bearer uDtfeAgTKL3_YnOxco4NV6B-WVZAIGyuzgH6Yp07FiV9K9ZRFOAa3r3YoxHVG1Gg")
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public static void main(String[] args) throws IOException {
OkHttpScript okHttpScript = new OkHttpScript();
String response = okHttpScript.run("http://api.genius.com/songs/378195/");
System.out.println(response);
}
}
当我运行此脚本时,出现 403 错误:
{"meta":{"status":401,"message":"This call requires an access_token. Please see: https://genius.com/developers"}}
作为引用,这是我与 Postman 发出相同请求的图片,并且它有效:
关于问题可能是什么的任何想法吗?
编辑:
不确定这是否正常,但是当我打印出构建的请求对象时,我没有看到请求中有 header 的迹象:
Request{method=GET, url=http://api.genius.com/songs/378195/, tag=null}
这就是我得到的。这可能是问题的一部分吗?
编辑2:
没关系,做一下
System.out.println(newRequest.headers());
给出了我最初输入的内容:
Authorization: Bearer 4mfDBVzCnp2S1Fc0l0K0cfqOrQYjRrb-OHi8W1f-PPU7LNLI6-cXY2E727-1gHYR
最佳答案
所以我弄清楚了我的问题是什么。我不确定其背后的详细信息,但我应该使用我的 URL https://api.genius.com/songs/378195/
而不是 http://api.genius.com/songs/378195/
Postman 似乎可以使用 http,但 OkHttp 需要 https。
关于java - 请求在 postman 中工作正常,但在 OkHTTP 中收到 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993819/