2012-03-10 76 views
0

我正在尝试使用简单的Java程序与Google进行身份验证。我用我的凭证发布到正确的URL。我收到了HTTP状态代码200的响应,但没有包含我需要为用户检索提要的任何身份验证令牌。下面的代码使用Java apache http令牌进行Google身份验证

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){ 
    } 
+0

这是你在发布你的代码示例时发生了一个错误,还是在'Content-'和你的其余URL之间真的有两个空格? – Perception 2012-03-10 13:36:27

+0

啊,对不起,它只是一个错字。 – user1261046 2012-03-10 13:38:57

回答

1

好吧,你有第一个问题是,“内容类型”需要一个头,而不是一个请求参数。其次,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()); 
+0

它的工作原理,但仍然没有得到响应中的SID,LSID和Auth cookie。我确实得到了一个状态200,这意味着它应该被认证,但我没有得到令牌 – user1261046 2012-03-10 14:00:03

+0

当我在REST客户端中发布这个请求时,我在响应正文中获得了SID和LSID,而不是标头。 – Perception 2012-03-10 14:01:55

+0

太棒了,谢谢。但是从我读的内容来看,不应该使用SID和LSID,而应该使用Auth令牌。事情是,我无法在响应主体中找到Auth令牌。对此有何想法? – user1261046 2012-03-10 14:25:58

相关问题