【问题标题】:WebView : setCookie to show a private image inside custom htmlWebView : setCookie 在自定义 html 中显示私有图像
【发布时间】:2019-08-20 15:05:18
【问题描述】:

我有以下图片。

http://example.com/system/files/private/fd41dbdea705d275aa2f5cf09c33731732f82c6d11c1951c5faa570059d52911989001fce5870053c0deeed85c028def20b18502108ad8d5d329ad007f45778c.JPG

这是一个私有路径,因此需要一个有效的 cookie 来获取它。 所以我使用这段代码在我的 webView 中显示它:

    CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(myWebView.getContext());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.removeSessionCookie();
    cookieManager.setCookie("http://example.com",cookie);
    cookieSyncManager.sync();

    String getcookie = cookieManager.getCookie("http://example.com");
    MyLog.myLog("getcookie "+getcookie);

    myWebView.setWebViewClient(new WebViewClient());
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.setWebChromeClient(new WebChromeClient());

    myWebView.loadUrl("http://example.com/system/files/private/fd41dbdea705d275aa2f5cf09c33731732f82c6d11c1951c5faa570059d52911989001fce5870053c0deeed85c028def20b18502108ad8d5d329ad007f45778c.JPG");

它工作正常。我可以正确地看到图像。所以我猜cookie代码是有效的。

现在我需要在自定义 html 文件 (privateimage_test.html) 中显示图像:

.....
.....
<div>
  <img src="http://example.com/system/files/private/fd41dbdea705d275aa2f5cf09c33731732f82c6d11c1951c5faa570059d52911989001fce5870053c0deeed85c028def20b18502108ad8d5d329ad007f45778c.JPG" style="width:100%">
</div>
.......

现在我的 java 代码除了最后一行是一样的:

myWebView.loadUrl("file:///android_asset/privateimage_test.html");

在这种情况下,我看不到我的图像。 如果我用我的 html 文件中的任何公共图像替换私有图像,它工作正常。所以我猜是cookie问题。

有什么帮助吗? 谢谢。

【问题讨论】:

    标签: android image cookies webview setcookie


    【解决方案1】:

    如果您尝试从存储在/assets 中的 html 加载图像,请记住该图像的路径必须定义为“file:///android_asset/...”

    没关系:

    myWebView.loadUrl("file:///android_asset/privateimage_test.html");
    

    但定义到privateimage_test.html 中的图像必须有路径

    <img src="file:///android_asset/html/<"Image file name">" >
    

    如果您从存储在 /assets 中的 .html 文件加载图像时遇到问题

    <div>
      <img src="http://example.com/system/files/private/myimage.JPG" style="width:100%">
    </div>
    

    记得已经定义了访问互联网的权限。

     <uses-permission android:name="android.permission.INTERNET"/>
    

    请记住使用https:// 定义的网址而不是http://,因为您在使用Android 9+ 时会遇到问题。

    【讨论】:

    • 我不想从 /assets 加载图像
    • @user2132478 您是否尝试从 Internet 加载但路径是在 html 文件中定义的?
    • 没错。我正在尝试使用 html 文件中定义的路径从 Internet 加载它。但这是一个私有图像:您需要一个有效的 cookie 才能获取图像。
    • @user2132478 检查图片的网址并检查您的互联网权限1 :-)。
    • 我的网络权限没问题。如果我直接在 webView 中加载图像的路径就可以正常工作。但我需要在 html 文件中定义它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    相关资源
    最近更新 更多