【发布时间】:2017-06-19 00:41:25
【问题描述】:
我正在尝试向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 提出相同请求的图片,它有效:
关于问题可能是什么的任何想法?
编辑:
不确定这是否正常,但是当我打印出构建的请求对象时,我看不到请求中有标头的迹象:
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
【问题讨论】:
-
尝试使用 Wireshark 看看实际的 HTTP 请求有何不同。
标签: java rest api okhttp okhttp3