【问题标题】:Request working fine in postman, but getting a 403 in OkHTTP请求在邮递员中工作正常,但在 OkHTTP 中得到 403
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      How to handle auth0 403 error without adding specific code everywhere (Retrofit/okhttp/RxAndroid)

      【讨论】:

      • 那不就是在失败的时候重新调用吗?如果我没有需要刷新的令牌,编写拦截器会对我有帮助吗?在我的情况下,令牌本身保持静态。
      • 不管是不是拦截器都不能解释为什么这个请求没有成功。
      【解决方案4】:

      *使用 Alex Hermstad 答案

      --> 在 android 中使用 https 而不是 http, Postman 似乎可以使用 http,但 OkHttp 需要 https。

      我因为这个错误 403 在 android 中被禁止而被困了一天,但在 Postman 中成功了 200 次。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-16
      • 2016-10-23
      • 1970-01-01
      • 2019-08-25
      • 2021-09-24
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      相关资源
      最近更新 更多