我正在尝试向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);
}
}
Run Code Online (Sandbox Code Playgroud)
运行此脚本时,出现 403 错误:
{"meta":{"status":401,"message":"This call requires an access_token. Please see: https://genius.com/developers"}}
Run Code Online (Sandbox Code Playgroud)
作为参考,这是我向 Postman 提出相同请求的图片,它有效:
关于问题可能是什么的任何想法?
编辑:
不确定这是否正常,但是当我打印出构建的请求对象时,我看不到请求中有标头的迹象:
Request{method=GET, url=http://api.genius.com/songs/378195/, …Run Code Online (Sandbox Code Playgroud) 所以我在 Spring Boot 中有一个 web 应用程序,并且有一部分我向 API 发出了许多 HTTP 请求,如果发出的请求太多,它似乎会超时。我听说从同步请求切换到异步请求可能有助于解决这个问题。
使用 OkHttp,这就是我的同步 GET 请求的样子:
private JSONObject run(String url) throws Exception {
Request newRequest = new Request.Builder()
.url(url)
.addHeader("Authorization", token)
.build();
try (Response response = client.newCall(newRequest).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
return new JSONObject(response.body().string());
}
}
Run Code Online (Sandbox Code Playgroud)
我通过解析响应正文将响应作为 JSON 对象返回。但是,在尝试使用 OkHttp 异步调用时,似乎无法使用相同的方法。这是我到目前为止:
public void runAsync(String url) throws Exception {
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", token)
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException …Run Code Online (Sandbox Code Playgroud)