如何使用android 2.2在请求头中设置sessionID

时间:2012-01-30 20:34:24

标签: android http http-headers

我正在使用android 2.2开发一个应用程序。我不知道如何管理服务器和移动应用程序之间的打开会话。当用户输入他的用户名和密码时,我有一个带登录屏幕的移动应用程序,我使用以下代码将其发送到服务器(php页面):

    httpMethod = new HttpPost(Constants.IOGIN_URL);
        httpMethod.setHeader("Accept", "text/html");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", userID));
        nameValuePairs.add(new BasicNameValuePair("password", pass));
        httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpMethod);
        HttpEntity input = response.getEntity();

当服务器接收到这些数据时,它会为该用户创建一个会话并发回成功代码。我想知道如何读取响应头的会话ID以及如何将其设置为每个下一个请求头。

1 个答案:

答案 0 :(得分:1)

我认为这会让你明白这一点。 您必须抓取cookie并将其包含在HTTP请求中。

从登录请求中获取Cookie:

HttpClient httpclient = new DefaultHttpClient();
    try {
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();

        // Create local HTTP context
        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpGet httpget = new HttpGet("http://www.yourpage/");

        System.out.println("executing request " + httpget.getURI());

        // Pass local context as a parameter
        HttpResponse response = httpclient.execute(httpget, localContext);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        // Consume response content
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

然后将它们作为当地意见传递:

HttpPost httppost = new HttpPost("http://www.yourpage/");

// Pass local context as a parameter     
HttpResponse response = httpclient.execute(httppost, localContext);