在Android中分享HTTPURLConnection与webview之间的会话

时间:2014-12-15 11:05:32

标签: java android jsp session android-webview

我正在开发一个应用程序,当登录成功时向服务器发送请求以进行登录验证然后我在会话中设置用户名&我的会话已创建。我在webview上显示服务器的jsp页面,所以我的jsp页面需要会话,但是他们没有找到任何会话,因为它是由HTTPURLConnection创建的。所以我想知道如何将HTTPURLConnection的会话分享到webview。

设置会话的代码

String uname=request.getparameter("Username");
if(LoginSucesss)
{
    session.setAttribute("uid",uname);
}

请不要将此问题标记为重复,因为它是原始的。

提前致谢

1 个答案:

答案 0 :(得分:0)

@Override
protected void onCreate(Bundle savedInstanceState) {
    // Get cookie manager for WebView
    // This must occur before setContentView() instantiates your WebView
    android.webkit.CookieSyncManager webCookieSync =
        CookieSyncManager.createInstance(this);
    android.webkit.CookieManager webCookieManager =
        CookieManager.getInstance();
    webCookieManager.setAcceptCookie(true);

    // Get cookie manager for HttpURLConnection
    java.net.CookieStore rawCookieStore = ((java.net.CookieManager)
        CookieHandler.getDefault()).getCookieStore();

    // Construct URI
    java.net.URI baseUri = null;
    try {
        baseUri = new URI("http://www.example.com");
    } catch (URISyntaxException e) {
        // Handle invalid URI
        ...
    }

    // Copy cookies from HttpURLConnection to WebView
    List<HttpCookie> cookies = rawCookieStore.get(baseUri);
    String url = baseUri.toString();
    for (HttpCookie cookie : cookies) {
        String setCookie = new StringBuilder(cookie.toString())
            .append("; domain=").append(cookie.getDomain())
            .append("; path=").append(cookie.getPath())
            .toString();
        webCookieManager.setCookie(url, setCookie);
    }

   //TODO:Your Code
}