Android: log into website and preserve session/cookie using DefaultHttpClient

前端 未结 4 1678
死守一世寂寞
死守一世寂寞 2021-02-08 11:08

I\'ve been through different tutorials and this website, but couldn\'t find a proper solution. On the other hand, I\'ve seen apps logging into websites and requesting further in

4条回答
  •  孤独总比滥情好
    2021-02-08 11:41

    You can do it this way, though it's rather a workaround.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        WebView webv = (WebView)findViewById(R.id.MainActivity_webview);         
        webv.setWebViewClient(new WebViewClient(){
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
        });
    
        String postData = FIELD_NAME_LOGIN + "=" + LOGIN +
                "&" + FIELD_NAME_PASSWD + "=" + PASSWD;
    
        // this line logs you in and you stay logged in
        // I suppose it works this way because in this case WebView handles cookies itself
        webv.postUrl(URL, EncodingUtils.getBytes(postData, "utf-8"));
    }
    

提交回复
热议问题