且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

与Android的饼干PHP登录

更新时间:2023-12-03 20:39:16

该Cookie一般应该由HttpClient的正确处理:你只需要使用同一个HttpClient的实例来登录你用你的实际要求,以及饼干应该在所有请求进行维护。作为一个例子,这是我用一个特定的登录序列:在我的情况下,我用一个位置重定向是成功的象征,但是你可以用200 OK状态行模式。如果返回true,则在HttpClient的实例会议的cookie存储有相应的cookie,我可以访问任何保护的URL就好了。

The cookie should generally be handled by the HttpClient correctly: you just have to use the same HttpClient instance to log in that you use for your actual requests, and the cookie should be maintained across all requests. As an example, this is a specific login sequence I use: in my case I use a Location redirect as a success symbol, but you can use a 200 OK status line instead. If this returns true then the cookie store in the HttpClient instance session has the appropriate cookie and I can access any protected URLs just fine.

public synchronized boolean login() throws Exception
    {
    HttpGet httpget;
    HttpPost httpost = new HttpPost(base + "auth/login");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("username", this.username));
    nvps.add(new BasicNameValuePair("password", this.password));
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    HttpResponse r = session.execute(httpost);

    // verify it succeeded
    HttpEntity entity = r.getEntity();
    Header lhdr = r.getFirstHeader("Location");
    if (lhdr != null) {
        // failed
        System.err.println("Login request failed:");
        if (entity != null && entity.getContentEncoding() != null) {
        dump("Login Request",
             new InputStreamReader(entity.getContent(), entity
                       .getContentEncoding().getValue()));
        }
        return false;
    }
    if (entity != null) entity.consumeContent();    
    return true;
    }