2013-02-21 104 views
0

我已成功獲得authorization_code"Error" : "invalid_request"authorization_code-token exchange的迴應。
這是我的Java代碼來獲得谷歌的OAuth令牌交換authentication_code:
(HTTP請求利用了HttpComponents爲什麼Google OAuth 2.0代碼令牌交換返回「invalid_request」?

String urlString = "https://accounts.google.com/o/oauth2/token"; 
String client_id = "<my_client_id>"; 
String client_secret = "<my_client_secret>"; 
String redirect_uri = "<my_redirect_url>"; 
String grant_type = "authorization_code"; 
HttpParams params = new BasicHttpParams(); 
params.setParameter("code", code); 
params.setParameter("client_id", client_id); 
params.setParameter("client_secret", client_secret); 
params.setParameter("redirect_uri", redirect_uri); 
params.setParameter("grant_type", grant_type); 
HttpPost post = new HttpPost(urlString); 
post.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
post.setParams(params); 
DefaultHttpClient httpClient = new DefaultHttpClient(); 
try { 
    HttpResponse response = httpClient.execute(post); 
    HttpEntity entity = response.getEntity(); 
    System.out.println(response.toString()); 
    DataInputStream in = new DataInputStream(entity.getContent()); 
    String line; 
    while ((line = in.readLine()) != null) { 
     System.out.println(line); 
    } 
} 

收到以下錯誤響應:

HTTP/1.1 400 Bad Request [Cache-Control: no-cache, no-store, max-age=0, must-revalidate, Pragma: no-cache, Expires: Fri, 01 Jan 1990 00:00:00 GMT, Date: Thu, 21 Feb 2013 11:39:04 GMT, Content-Type: application/json, X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, X-XSS-Protection: 1; mode=block, Server: GSE, Transfer-Encoding: chunked] 
{ 
    "error" : "invalid_request" 
} 

是有什麼辦法可以知道究竟是什麼導致了錯誤?
或者您是否可以找到請求的任何錯誤?

+0

看起來很不錯。任何方式來捕獲實際的HTTP發佈流量? 400我的經驗意味着語法錯誤。你的代碼不包括你如何使用urlString做「發佈」,但我認爲這是一個不容易的事情;也看不到像post.setHeader(「Content-Type」,「application/x-www-form-urlencoded」); – 2013-02-22 05:04:54

+0

更新了問題 – 2013-02-22 05:12:31

回答

2

儘管我沒有Apache庫的個人經驗,但它看起來像參數作爲查詢參數發送而不是發佈的表單參數。根據這個HttpClient Quick Start,它應該看起來像:

HttpPost httpPost = new HttpPost(urlString); 
List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
nvps.add(new BasicNameValuePair("code", code)); 
nvps.add(new BasicNameValuePair("client_id", client_id)); 
nvps.add(new BasicNameValuePair("client_secret", client_secret)); 
nvps.add(new BasicNameValuePair("redirect_uri", redirect_uri)); 
nvps.add(new BasicNameValuePair("grant_type", grant_type)); 
httpPost.setEntity(new UrlEncodedFormEntity(nvps)); 
HttpResponse response = httpclient.execute(httpPost); 
相關問題