2014-09-05 24 views
0

我需要設置一個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相同的請求,這工作正常。

+0

我複製粘貼你的代碼,只改變URL爲'https:// httpbin.org/get',標題爲隨機單詞。標題在請求中正確發送,所以這似乎不是問題。也許你的授權標題不正確?嘗試檢查'prepareURLWithOAuthSignature'實際返回的內容。 – Wiwiweb 2014-09-05 18:05:30

+0

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

+0

是你應該在該字符串之前有一個授權方案? – chrylis 2014-09-05 18:18:51

回答

0

以正確的方式添加標題,看起來您不知道401錯誤是否由標頭中缺少的Authorization標頭或錯誤的值引起。

您應該嘗試將您的請求發送到諸如myhttp.infowhatismybrowser之類的網站,該網站將返回請求中的所有標題。只需在標準輸出上打印它們,這樣您就可以確定是否發送了標題。

+0

由於..似乎頭與請求一起發送。需要調查爲什麼現在會拋出403?順便說一句,它現在拋出403。 – user1356042 2014-09-06 13:45:20