【问题标题】:Java HttpUrlConnection - 401 with authentication headersJava HttpUrlConnection - 401 与身份验证标头
【发布时间】:2015-12-01 01:38:06
【问题描述】:

我可能做错了什么,但使用 Curl/Rest 客户端,我可以使用 Oauth2 生成的令牌向服务器发送 http 请求,详细信息如下:

url: https://blah.blah
Authorization: OAuth <oauth token>
Accept: application/blah (I'm hiding some of the details...)

使用 Curl/Rest 可以正常工作,并且我按预期返回了 JSON 对象。但是,在 Java 中执行此操作时,我每次都会得到 401。我猜我搞砸了以某种方式附加标题,但我看不出如何。

url = new URL(baseUrl+ reqUrl);
    System.out.println("Querying API with the following url:" + url.toString());

    httpReq = (HttpURLConnection) url.openConnection();
    httpReq.addRequestProperty("Authorization: OAuth ", token.trim());
    httpReq.addRequestProperty("Accept", "application/blah...");
    httpReq.connect();

我猜我的标题设置有误,但我不知道怎么做。有没有更好的方法来实现 http 请求的标头?

任何意见或建议将不胜感激。 谢谢

【问题讨论】:

标签: java http httpurlconnection


【解决方案1】:

你在 curl 中设置 Authorization: OAuth 而在代码中我看到你在做 Authorization: 我看到 OAuth 丢失了,我希望这个不是问题。

【讨论】:

  • 你说得对,我错过了这一点。我刚刚更新了它,但同样的事情正在发生。感谢您注意到这一点!
【解决方案2】:

不要在 addRequestProperty() 或 setRequestProperty() 的密钥规范中包含“OAuth”。所以这是不正确的:

httpReq.addRequestProperty("Authorization: OAuth ", token.trim()); 

相反,它应该是值的一部分:

String header = "OAuth oauth_token=\"ConsumerKey%3D...\",oauth_consumer_key=\"...";
httpReq.setRequestProperty("Authorization", header);

以上应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 2014-08-05
    • 2015-01-25
    • 2022-10-13
    • 2019-06-19
    • 2021-09-26
    • 2015-03-07
    • 2015-09-09
    相关资源
    最近更新 更多