What is wrong with the implementation of the POST request?

I am working on Google OAuth 2.0 with java and got into an unknown error during implementation.
The following CURL request for POST works fine:

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 

And produces the desired result.
But the following implementation of the above POST request in java causes some error and response in "invalid_request"
Check the following code and indicate what happens here: (using the Apache http components)

 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); 

Tried URLEncoder.encode( param , "UTF-8") for each parameter, but this does not work either.
What could be the reason?

+7
source share
1 answer

You must use UrlEncodedFormEntity not setParameter in the message. It also handles the Content-Type: application/x-www-form-urlencoded header 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); 
+16
source

All Articles