小编Ale*_*tad的帖子

请求在邮递员中工作正常,但在 OkHTTP 中得到 403

我正在尝试向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)

java api rest okhttp okhttp3

5
推荐指数
1
解决办法
6479
查看次数

Java - 从 OkHttp 异步 GET 检索结果

所以我在 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)

java spring asynchronous okhttp okhttp3

2
推荐指数
1
解决办法
2356
查看次数

标签 统计

java ×2

okhttp ×2

okhttp3 ×2

api ×1

asynchronous ×1

rest ×1

spring ×1