android如何维护会话

时间:2015-01-29 11:28:37

标签: php android web-services session-cookies

我正在android中构建一个登录应用程序,我正在点击一个url(使用用户名和密码),直到该部分它工作正常,但在那之后每当我点击一个url(一旦用户通过身份验证),它就不会返回任何内容(即出现错误消息,请先登录)。

我到了某处,这是phpSessionId的错误(即会话被销毁以获得进一步的请求)如果我们希望我们的Android应用程序在服务器端保持身份验证,我们需要在第一次连接后获取该ID然后发送它在我们所有后续请求的标题中。

但问题是我无法从第一个连接的标头获取sessionId,并将其与标头一起发送进一步的请求。

请给我一些代码或链接以正确完成任务。感谢。

1 个答案:

答案 0 :(得分:0)

最后,我解决了Android中的会话处理问题。 Android无法处理会话本身(简单的浏览器可以),因此我们必须明确处理它。我稍微更改了http连接的代码。在建立连接时在第一个Activity中创建DefaultHttpClient的实例

public static DefaultHttpClient httpClient;

第一次连接时,我做了以下事情:

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {

        // http client

        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = MainActivity.httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = MainActivity.httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

}

并按以下方式致电

jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

这也有助于我解决Android中的会话问题。

相关问题