2012-08-29 68 views
2

感謝stackoverflow,我設法實現了一個webview,我可以通過長按上下文菜單/ HitTestResult保存圖像。所以,當我得到的圖像的URL,我做這樣的事情:Android WebView:通過身份驗證從網站保存圖像

URL url = new URL(yourImageUrl); 
     InputStream is = (InputStream) url.getContent(); 
     byte[] buffer = new byte[8192]; 
     int bytesRead; 
     ByteArrayOutputStream output = new ByteArrayOutputStream(); 
     while ((bytesRead = is.read(buffer)) != -1) { 
     output.write(buffer, 0, bytesRead); 
     } 

then put the output.toByteArray() into a FileOutputStream; 

對於「正常」的網站能正常工作,圖像存儲在SD卡中。

但是我仍然不知道(我在這方面做了大量的搜索:-(如何下載需要某種認證的網站的圖片,例如,我進入網站並輸入用戶名/密碼(一些服務器端的語言,如PHP),這給我帶來了一些圖片.WebView在登錄和顯示所有內容時沒有問題,但是我無法保存圖像,因爲身份驗證(webview中存在)是出現在我的圖像保存機制。

與上面的代碼,我只是得到了URL.getContent()一個FileNotFoundException異常。 然後我試圖使用的HttpClient和HTTPGET/HttpResponse對象,其中反應總是代碼403.

我的問題: 如何訪問/下載/驗證以獲取受保護區域的圖像(可能是通過服務器端語言或基本身份驗證)。

我的意思是......它都在那裏,在WebView中正確顯示和驗證:-( 但是,WebView的內容與我的URL/Http請求下載工作之間沒有任何聯繫.Webview可以以某種方式分享它的身份驗證狀態?

我甚至想過從WebView緩存中獲取圖像,因爲它全部在那裏。(但是我無法知道如何做到這一點)...是否沒有機制可以獲得該圖像以某種方式直接退出WebView?

我會感謝任何形式的幫助!

回答

0

如果驗證方法是使用cookie,下面的方法可能工作:

首先,在你的WebView同步餅乾裝網址前:

CookieSyncManager cookieSyncManager = 
        CookieSyncManager.createInstance(webView.getContext()); 
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.setAcceptCookie(true); 
cookieSyncManager.sync(); 

接下來,當請求你的形象,你可以把餅乾在您的http請求標題域中獲取HttpResponse的內容:

String cookies = CookieManager.getInstance().getCookie(yourImageUrl); 
HttpClient httpClient = new DefaultHttpClient(); 
HttpContext localContext = new BasicHttpContext(); 
HttpGet httpGet   = new HttpGet(yourImageUrl); 
httpGet.setHeader("Cookie", cookies); 

HttpResponse httpResponse = httpClient.execute(httpGet, localContext); 
HttpEntity httpEntity  = httpResponse.getEntity(); 
InputStream is   = httpEntity.getContent(); 
相關問題