我需要设置一个HTTPS GET请求和首部的OAuth认证报头要被设置的认证报头是如下如何设置HttpsURLConnection的
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,[email protected]}", "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头,因此服务器返回401
不知道如何解决这个问题。
注:我试图执行从POSTMAN相同的请求,这工作正常。
我复制粘贴你的代码,只改变URL为'https:// httpbin.org/get',标题为随机单词。标题在请求中正确发送,所以这似乎不是问题。也许你的授权标题不正确?尝试检查'prepareURLWithOAuthSignature'实际返回的内容。 – Wiwiweb 2014-09-05 18:05:30
prepareURLWithOAuthSignature返回下面的头 - OAuth的oauth_consumer_key = “vrnx4dpg6c356c6e8pp6ep74”,oauth_signature_method = “HMAC-SHA1”,oauth_timestamp = “1409940580”,oauth_nonce = “x1409940580758”,oauth_version = “1.0”,oauth_signature = “y82y6Halc4Y9bcDuMgP1cxjSUsw =” – user1356042 2014-09-05 18:10:23
是你应该在该字符串之前有一个授权方案? – chrylis 2014-09-05 18:18:51