Maintaining session in android ( application stay authenticated on the server side)

后端 未结 5 1681
太阳男子
太阳男子 2020-11-29 16:29

I am building a login application in android in which i am hitting a url(with username and password) upto that part it works fine but after that whenever I am hitting a url(

5条回答
  •  猫巷女王i
    2020-11-29 17:21

    I wrote a post about it a while back on coderwall It uses the HttpRequestInterceptor and HttpResponseInterceptor classes which are perfect for that kind of scenario.

    Here is an example:

    public class HTTPClients {
    
    private static DefaultHttpClient _defaultClient;
    private static String session_id;
    private static HTTPClients _me;
    private HTTPClients() {
    
    }
    public static DefaultHttpClient getDefaultHttpClient(){
        if ( _defaultClient == null ) {
            _defaultClient = new DefaultHttpClient();
            _me = new HTTPClients();
            _defaultClient.addResponseInterceptor(_me.new SessionKeeper());
            _defaultClient.addRequestInterceptor(_me.new SessionAdder());
        }
        return _defaultClient;
    }
    
    private class SessionAdder implements HttpRequestInterceptor {
    
        @Override
        public void process(HttpRequest request, HttpContext context)
                throws HttpException, IOException {
            if ( session_id != null ) {
                request.setHeader("Cookie", session_id);
            }
        }
    
    }
    
    private class SessionKeeper implements HttpResponseInterceptor {
    
        @Override
        public void process(HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            Header[] headers = response.getHeaders("Set-Cookie");
            if ( headers != null && headers.length == 1 ){
                session_id = headers[0].getValue();
            }
        }
    
    }
    

    }

提交回复
热议问题