Android应用程序 - 通过HTTP Post进行Google授权

时间:2011-03-11 17:28:42

标签: java android debugging httpclient http-post

我只是想通过HTTP POST发送我的Google帐户身份验证数据。我已经构建了HTTPpost(URLencoded the ArrayList name - value pair)并执行HTTPClient来获取HTTPResponse。然而,这是问题开始的地方,我回来的HTTPResponse似乎在我尝试调用其关联方法之一时返回异常(getStatusLine或getEntity)。我还试图通过做一个简单的“if(null)else”类型检查来检查“null”响应,但仍然没有运气。

这是问题因为我正在使用模拟器吗?

----- ----- UPDATE

我发现我收到一个NULL指针响应,导致异常。因此,我访问Google API的方式存在问题。网址为“https://www.google.com/accounts/ClientLogin”,“Email”和“Passwd”是我用于POST请求的两个参数。

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("<URL HERE>");

try {

    List<NameValuePair> parameters = new ArrayList<NameValuePair>(2);
    parameters.add(<name_value_pair>);
    parameters.add(<name_value_pair>); 
    httppost.setEntity(new UrlEncodedFormEntity(parameters));


    HttpResponse response = httpclient.execute(httppost);

    StatusLine returned_status = response.getStatusLine();
    int status_code = returned_status.getStatusCode();


} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

}

1 个答案:

答案 0 :(得分:2)

而是使用httpPost使用HttpRequest&amp;你也必须使用名为Base64&amp;的库。 Android 2.1及以上版本

    String data;
    HttpParams httpParameters;


   HttpClient client;
    HttpResponse response;
    String userAuth;

    httpParameters = new BasicHttpParams();
                    String auth = android.util.Base64.encodeToString(
                            (username + ":" + userpwd).getBytes("UTF-8"), 
                            android.util.Base64.NO_WRAP
                        );
                        HttpGet request = new HttpGet(StaticURL.uMain+resourceURI);

                        request.addHeader("Authorization", "Basic "+ auth);

                    HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
                    client = new DefaultHttpClient(httpParameters);

                    response = client.execute(request);
                    userAuth = EntityUtils.toString(response.getEntity());

                    System.out.println("Data. in login.."+userAuth);