登录后再次发送并收到cookie

时间:2014-02-28 20:31:50

标签: java android

我正在开发一个登录服务,记录用户,然后在成功登录后,它再次发布到一个新的脚本,其中包含登录时提供的cookie以获取更多信息。这是我的登录帖子:

@Override
        protected Boolean doInBackground(Void... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://testsite.com/login");

            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("userid", "john"));
                nameValuePairs.add(new BasicNameValuePair("password", "test"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);
                String TAG = "com.imtins.worryfree";
                String responseAsText = EntityUtils.toString(response.getEntity());

                Log.d(TAG, "Response from server: " + responseAsText.toString());

            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }

现在从我读过的内容如果我使用相同的hpptClient而不开始新的,当我做另一个帖子时它将使用我收到的cookie?我可以在哪里添加我的示例中的第二篇文章或它看起来如何。刚刚开始使用android / Java,这对我来说有点混乱。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用HttpContext + CookieStore来跟踪请求之间的cookie状态。我认为这样的事情对你有用(未经测试):

    @Override
    protected Boolean doInBackground(Void... params) {
        HttpClient httpclient = new DefaultHttpClient();

        CookieStore cookieStore = new BasicCookieStore();
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpPost httppost = new HttpPost("http://testsite.com/login");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("userid", "john"));
            nameValuePairs.add(new BasicNameValuePair("password", "test"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost, localContext);
            String TAG = "com.imtins.worryfree";
            String responseAsText = EntityUtils.toString(response.getEntity());

            Log.d(TAG, "Response from server: " + responseAsText.toString());

        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }

对于第二个请求,请重用localContext变量:

        // replace XXX below with correct URL
        httppost = new HttpPost("http://testsite.com/XXXXXX");

        try {
            // set entities here ...

            HttpResponse response = httpclient.execute(httppost, localContext);
            String TAG = "com.imtins.worryfree";
            String responseAsText = EntityUtils.toString(response.getEntity());

            Log.d(TAG, "Response from server: " + responseAsText.toString());

        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }