2014-09-05 27 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