Java 如何设置HttpsURLConnection的身份验证标头
我需要设置HTTPS GET请求的OAuth身份验证头,要设置的头如下Java 如何设置HttpsURLConnection的身份验证标头,java,Java,我需要设置HTTPS GET请求的OAuth身份验证头,要设置的头如下 Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxx" ,oauth_signature_method="HMAC-SHA1" ,oauth_timestamp="1409861973" ,oauth_nonce="x1409861973681" ,oauth_version="1.0" ,oauth_signature="M+Dq62XboEd3+t6VDIcLy8
Authorization: OAuth oauth_consumer_key="xxxxxxxxxxxxxx" ,oauth_signature_method="HMAC-SHA1" ,oauth_timestamp="1409861973" ,oauth_nonce="x1409861973681" ,oauth_version="1.0" ,oauth_signature="M+Dq62XboEd3+t6VDIcLy86zlQg="
我使用下面的java代码
String url = null;
try {
url = "https://secure.api.abc.net/data/ServiceAccount?schema=1.0&byBillingAccountId=" + URLEncoder.encode("{EQUALS,acc@xyz.edu}", "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String header = OAuthClient.prepareURLWithOAuthSignature(url1);
HttpsURLConnection con = null;
try {
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", header);
int responseCode = con.getResponseCode();
System.out.println("Response Code = " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
//print result
System.out.println("Response = " + response.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(con!=null) con.disconnect();
}
似乎con.setRequestProperty(“Authorization”,header)没有设置授权头,因此服务器返回401
你知道怎么解决这个问题吗
注意:我试图执行来自POSTMAN的相同请求,但效果很好。您以正确的方式添加了标头,并且似乎不知道401错误是由缺少
授权
标头还是标头中的错误值引起的
您应该尝试将您的请求发送到或之类的网站,该网站将返回您请求中的所有标题。只需将它们打印在标准的ourput上,这样您就可以确定是否发送了标题。我认为Oauth签名似乎缺少所需的最终URL编码。应以等号编码的3D结尾 我复制粘贴了您的代码,仅将url更改为
https://httpbin.org/get
和随机单词的标题。请求中正确发送了头,所以这似乎不是问题所在。可能您的授权标头不正确?尝试检查实际返回的内容。prepareURLWithOAuthSignature返回以下标题-OAuth OAuth_consumer_key=“vrnx4dpg6c356c6e8pp6ep74”,OAuth_signature_method=“HMAC-SHA1”,OAuth_timestamp=“1409940580”,OAuth_nonce=“x1409940580758”,OAuth_version=“1.0”,OAuth_签名=“y82y6Halc4Y9bcDuMgP1cxjSUsw=”您应该在该字符串之前有一个授权方案吗?是的。事实上,它应该是授权:OAuth OAuth-U consumer-key=“vrnx4dpg6c356c6e8pp6ep74”,OAuth-U签名方法=“HMAC-SHA1”,OAuth-U时间戳=“1409861973”,OAuth-U nonce=“x1409861973681”,OAuth-U版本=“1.0”,OAuth-U签名=”M+Dq62XboEd3+t6VDIcLy86zlQg=“谢谢..头似乎与请求一起发送。需要调查它为什么现在抛出403?顺便说一句,它现在抛出403。