2013-02-25 48 views
7

我一直在使用java處理Google OAuth 2.0,並在實現過程中遇到了一些未知錯誤。
下面捲曲的POST請求正常工作:這個POST請求實現有什麼問題?

curl -v -k --header "Content-Type: application/x-www-form-urlencoded" --data "code=4%2FnKVGy9V3LfVJF7gRwkuhS3jbte-5.Arzr67Ksf-cSgrKXntQAax0iz1cDegI&client_id=[my_client_id]&client_secret=[my_client_secret]&redirect_uri=[my_redirect_uri]&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token 

,併產生所需的結果。
但在Java上述POST請求以下實施導致一些錯誤,並在"invalid_request"
檢查下面的代碼,並點怎麼回事錯在這裏的響應:(由使用Apache的HTTP組件)

HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token"); 
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); 
post.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
post.setParams(params); 
DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(post); 

試圖與每個參數爲URLEncoder.encode(param , "UTF-8"),但這也不起作用。
可能是什麼原因?

回答

16

您應該使用UrlEncodedFormEntity上後不的setParameter。 它也爲您處理Content-Type: application/x-www-form-urlencoded標題。

HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token"); 
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)); 

post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); 

DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(post); 
+0

這幫助!!!! – 2013-02-25 10:05:36

相關問題