2012-12-28 75 views
-1

我想攔截blobservice在我的Android應用程序的請求攔截Blob存儲請求和保存響應文件

到URL看起來像這樣: http://foo.appspot.com/simpleams/blobservice?blob-key=AMIfv94NAAoxn1oi_ySWYSiNF3MforFVI6SvDi_NeF0rjNr_QW

@Override 
public WebResourceResponse shouldInterceptRequest(WebView view, String url) { 
     if(url.contains("blobservice")) { 
      return getAppWebResourceResponseFromBlobstore(view, url); 
     } else { 
      return super.shouldInterceptRequest(view, url); 
     } 

    } 

private WebResourceResponse getAppWebResourceResponseFromBlobstore(WebView view, String url) { 
    try { 
     // TODO: 
        return file from local data or download it from 
        blob service, save it and return it... 
    } catch (IOException e) { 
     return null; 
    } 
} 

我怎樣才能使請求到服務器並在本地保存文件?

回答

0

我發現我自己的解決方案,並希望與大家分享:

private WebResourceResponse getAppWebResourceResponseFromBlobstore(WebView view, String url) { 


     int slashIndex = url.lastIndexOf("blobservice?blob-key="); 

     String key; 
     key = url.substring(slashIndex + "blobservice?blob-key=".length()); 

     System.out.println(key);  
       BlobstoreManager m = new BlobstoreManager(ctx, url); 


     return m.getBlob(key); 


    } 


public class BlobstoreManager{ 


    Context mContext; 
    String url; 

    public BlobstoreManager(Context c, String url) { 

     this.url = url; 
     this.mContext = c; 


    } 


    public WebResourceResponse getBlob(String key) { 

     String path = key; 
     File file = mContext.getFileStreamPath(key); 
     if(file.exists()) { 
      try { 
       System.out.println("Response from Blob"); 
       return new WebResourceResponse("", "",mContext.openFileInput(path)); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      try { 

       HttpClient httpclient = new DefaultHttpClient(); 
       HttpResponse response = httpclient.execute(new HttpGet(url)); 
       StatusLine statusLine = response.getStatusLine(); 
       if(statusLine.getStatusCode() == HttpStatus.SC_OK){ 
        FileOutputStream output = mContext.openFileOutput(path, Context.MODE_PRIVATE); 

        response.getEntity().writeTo(output); 

        output.flush(); 
        output.close(); 

       } else{ 
        //Closes the connection. 
        response.getEntity().getContent().close(); 
        throw new IOException(statusLine.getReasonPhrase()); 
       } 


      System.out.println("Save new Blob"); 
       return new WebResourceResponse("", "",mContext.openFileInput(path)); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     return null; 
    } 

}