我需要設置一個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