使用Java apache http令牌进行Google身份验证



我正在尝试使用一个简单的Java程序与Google进行身份验证。我用我的凭据发布到正确的URL。我得到了一个HTTP状态代码为200的响应,但其中不包含为用户检索提要所需的任何身份验证令牌。这是代码

private static String postData = "https://www.google.com/accounts/ClientLogin?Content-type=application/x-www-form-urlencoded&accountType=GOOGLE&Email=xxxxxxxx&Passwd=xxxxx";
public GoogleConnector(){
    HttpClient client=new DefaultHttpClient();
    HttpPost method=new HttpPost(postData);
    try{
        HttpResponse response=client.execute(method);
        System.out.println(response.toString());
    }
    catch(Exception e){ 
    }

好的,您遇到的第一个问题是"Content-Type"需要是一个标头,而不是一个请求参数。其次,POST参数应该附加到请求主体,而不是请求URL。你的代码应该是这样的:

HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost("https://www.google.com/accounts/ClientLogin");
method.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(4);
postParams.add(new BasicNameValuePair("accountType", "GOOGLE"));
postParams.add(new BasicNameValuePair("Email", "xxxxxxx"));
postParams.add(new BasicNameValuePair("Passwd", "xxxxxx"));
postParams.add(new BasicNameValuePair("service", "cl"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);
method.setEntity(formEntity);
HttpResponse response=client.execute(method);
System.out.println(response.toString());

最新更新