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

时间:2017-02-02 03:42:08

标签: java rest api okhttp okhttp3

我正在尝试向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提出同样要求的图片,它有效:

Postman picture

关于问题可能是什么的任何想法?

编辑:

不确定这是否正常,但是当我打印出构建的请求对象时,我看不到请求中有标题:

Request{method=GET, url=http://api.genius.com/songs/378195/, tag=null}

是我得到的。这可能是问题的一部分吗?

EDIT2:

没关系,做一个

System.out.println(newRequest.headers());

给了我最初的内容:

Authorization: Bearer 4mfDBVzCnp2S1Fc0l0K0cfqOrQYjRrb-OHi8W1f-PPU7LNLI6-cXY2E727-1gHYR

3 个答案:

答案 0 :(得分:0)

所以我弄清楚我的问题是什么。我不确定其背后的细节,但我应该使用我的网址https://api.genius.com/songs/378195/代替http://api.genius.com/songs/378195/

邮递员似乎对http很好,但OkHttp需要https。

答案 1 :(得分:0)

不确定你的服务器端是怎么写的,我今天在请求别人的服务时遇到了同样的问题。我的解决方案是更改 User-Agent,即使 PostmanRuntime/7.26.10

答案 2 :(得分:-1)