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

Request working fine in postman, but getting a 403 in OkHTTP

我正在尝试向 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 发出完全相同请求的照片,它有效:

对可能出现的问题有什么想法吗?

编辑:

不确定这是否正常,但是当我打印出构建的请求 object 时,我没有看到请求中有 headers 的迹象:

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

你应该为 okhttp 添加一个拦截器,这样应该可以工作

所以我想出了我的问题所在。我不确定它背后的细节,但我应该使用我的 URL has https://api.genius.com/songs/378195/ 而不是 http://api.genius.com/songs/378195/

Postman 似乎可以使用 http,但 OkHttp 需要 https。

不知道你的服务器端是怎么写的,我今天在请求别人的服务时遇到了同样的问题。我的解决方案是更改用户代理,即使 PostmanRuntime/7.26.10

*使用 Alex Hermstad 答案

--> 在 android 中使用 https 而不是 http, Postman 似乎对 http 没问题,但 OkHttp 需要 https。

我在 android 中因为这个错误 403 forbidden 而卡了一天,但是在 Postman 中给出了 200 success .