2013-02-25 13 views
7

私はJavaでGoogle OAuth 2.0を扱っており、実装中にいくつかの不明なエラーが発生しました。この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 

をし、必要な結果を生成します。
POSTリクエストに対して次のCURLが正常に動作します。
が、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

これは助けになりました!!!! –

関連する問題