此POST请求实现有什么问题? [英] What is wrong with this POST request implementation?

查看:106
本文介绍了此POST请求实现有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Java解决Google OAuth 2.0,并在实施过程中被一些未知的错误所震惊.
下列用于POST请求的CURL可以正常工作:

I have been working around Google OAuth 2.0 with java and got struck with some unknown error during implementation.
The following CURL for POST request 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

并产生所需的结果.
但是上面的POST请求在Java中的以下实现导致一些错误和"invalid_request"中的响应
检查以下代码,并在此处指出出了什么问题:(使用Apache http-components)

And produces the required result.
But the following implementation of above POST request in java causes some error and the response in "invalid_request"
Check the following code and point whats going wrong here:(made use of 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);

尝试对每个参数使用URLEncoder.encode( param , "UTF-8"),但这也不起作用.
可能是什么原因?

Tried with URLEncoder.encode( param , "UTF-8") for each parameter but that too doesn't work.
What might be the cause?

推荐答案

您应该在帖子中使用UrlEncodedFormEntity而不是setParameter. 它也为您处理Content-Type: application/x-www-form-urlencoded标头.

You should be using UrlEncodedFormEntity not setParameter on the post. It handles the Content-Type: application/x-www-form-urlencoded header for you too.

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

这篇关于此POST请求实现有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆