使用Android发送登录!

时间:2011-04-19 10:14:17

标签: android http cookies post

我在Android中有一个登录表单,我想用它向服务器发送HttpPost请求,如果登录成功则返回cookie。 我有一个问题,我如何实现这个的正确版本,如何获取cookie并将其存储在设备上(我将它存储在首选项数据库中?所以我可以在以后销毁它?)。

我现在有这个代码:

public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://a_site.com/logintest.aspx");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("txtUsername", "username"));
        nameValuePairs.add(new BasicNameValuePair("txtPassword", "123456"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        Log.v(TAG, "Response from server: " + response.toString());

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    }
}

如何获取cookie以及如果登录成功,我该如何存储?

2 个答案:

答案 0 :(得分:5)

不是自己编写,而是可以通过简单的方式完成:

import org.apache.http.util.EntityUtils;



HttpResponse response = httpclient.execute(httppost);
String responseAsText = EntityUtils.toString(response.getEntity());

答案 1 :(得分:2)

以下代码段将返回http响应的格式良好的字符串表示形式:

public String responseHandler(HttpResponse response)
{
    HttpEntity resEntity = response.getEntity();
            br = new BufferedReader(new InputStreamReader(
                    resEntity.getContent(), "UTF-8"));
            String line;
            String result = "";
            while (((line = br.readLine()) != null)) {              
                result = result + line + "\n";
            }

            return result;
}

如何选择存储结果是另一个问题,我建议使用某种全局变量。