List of usage examples for android.webkit WebResourceResponse WebResourceResponse
public WebResourceResponse(String mimeType, String encoding, InputStream data)
From source file:Main.java
/** * Load a resource as WebResourceResponse * @param context The current context./*from w w w. j a v a 2s . com*/ * @param resourceId The resource id. * @return The loaded string. */ public static WebResourceResponse getWebResourceResponseFromRawResource(Context context, int resourceId, String mime, String encoding) { WebResourceResponse result = null; InputStream is = context.getResources().openRawResource(resourceId); if (is != null) { result = new WebResourceResponse(mime, encoding, is); } else { result = null; } return result; }
From source file:com.concentricsky.android.khanacademy.util.CaptionManager.java
/** * Get a {@link WebResourceResponse} with subtitles for the video with the given youtube id. * /*from w w w .j av a 2s . c o m*/ * The response contains a UTF-8 encoded json object with the subtitles received * from universalsubtitles.org. * * @param youtubeId The youtube id of the video whose subtitles we need. * @return The {@link WebResourceResponse} with the subtitles, or {@code null} in case of error or if none are found. */ public WebResourceResponse fetchRawCaptionResponse(String youtubeId) { Log.d(LOG_TAG, "fetchRawCaptionResponse"); String youtube_url = "http://www.youtube.com/watch?v=" + youtubeId; try { URL url = new URL(String.format(subtitleFormat, youtube_url, "en")); URLConnection connection = url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setUseCaches(true); InputStream in = null; try { in = connection.getInputStream(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); //various exceptions including at least ConnectException and UnknownHostException can happen if we're offline } return in == null ? null : new WebResourceResponse("application/json", "UTF-8", in); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:nya.miku.wishmaster.http.cloudflare.InterceptingAntiDDOS.java
/** anti-DDOS , ? ? ?? webview httpclient (? ?? ? ?-? API >= 11) */ Cookie check(final CloudflareException exception, final ExtendedHttpClient httpClient, final CancellableTask task, final Activity activity) { synchronized (lock) { if (processing) return null; processing = true;/*from www. j a va2 s. co m*/ } processing2 = true; currentCookie = null; final HttpRequestModel rqModel = HttpRequestModel.builder().setGET().build(); final CookieStore cookieStore = httpClient.getCookieStore(); CloudflareChecker.removeCookie(cookieStore, exception.getRequiredCookieName()); final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView(); final WebViewClient client = new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { HttpResponseModel responseModel = null; try { responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task); for (int i = 0; i < 3 && responseModel.statusCode == 400; ++i) { Logger.d(TAG, "HTTP 400"); responseModel.release(); responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task); } for (Cookie cookie : cookieStore.getCookies()) { if (CloudflareChecker.isClearanceCookie(cookie, url, exception.getRequiredCookieName())) { Logger.d(TAG, "Cookie found: " + cookie.getValue()); currentCookie = cookie; processing2 = false; return new WebResourceResponse("text/html", "UTF-8", new ByteArrayInputStream("cookie received".getBytes())); } } BufOutputStream output = new BufOutputStream(); IOUtils.copyStream(responseModel.stream, output); return new WebResourceResponse(null, null, output.toInputStream()); } catch (Exception e) { Logger.e(TAG, e); } finally { if (responseModel != null) responseModel.release(); } return new WebResourceResponse("text/html", "UTF-8", new ByteArrayInputStream("something wrong".getBytes())); } }; activity.runOnUiThread(new Runnable() { @SuppressLint("SetJavaScriptEnabled") @Override public void run() { webView = new WebView(activity); webView.setVisibility(View.GONE); layout.addView(webView); webView.setWebViewClient(client); webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(exception.getCheckUrl()); } }); long startTime = System.currentTimeMillis(); while (processing2) { long time = System.currentTimeMillis() - startTime; if ((task != null && task.isCancelled()) || time > CloudflareChecker.TIMEOUT) { processing2 = false; } } activity.runOnUiThread(new Runnable() { @Override public void run() { try { layout.removeView(webView); webView.stopLoading(); webView.clearCache(true); webView.destroy(); webView = null; } finally { processing = false; } } }); return currentCookie; }
From source file:com.github.pockethub.android.accounts.LoginWebViewActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webView = new WebView(this); // Needs the be activated to allow GitHub to perform their requests. webView.getSettings().setJavaScriptEnabled(true); String userAgent = webView.getSettings().getUserAgentString(); // Remove chrome from the user agent since GitHub checks it incorrectly userAgent = userAgent.replaceAll("Chrome/\\d{2}\\.\\d\\.\\d\\.\\d", ""); webView.getSettings().setUserAgentString(userAgent); String url = getIntent().getStringExtra(LoginActivity.INTENT_EXTRA_URL); webView.loadUrl(url);/*from ww w . ja va 2s . c om*/ webView.setWebViewClient(new WebViewClient() { MaterialDialog dialog = new MaterialDialog.Builder(LoginWebViewActivity.this).content(R.string.loading) .progress(true, 0).build(); @Override public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) { dialog.show(); } @Override public void onPageFinished(android.webkit.WebView view, String url) { dialog.dismiss(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(android.webkit.WebView view, WebResourceRequest request) { return shouldIntercept(request.getUrl().toString()); } @Override public WebResourceResponse shouldInterceptRequest(android.webkit.WebView view, String url) { return shouldIntercept(url); } @Override public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) { Uri uri = Uri.parse(url); return overrideOAuth(uri) || super.shouldOverrideUrlLoading(view, url); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) { return overrideOAuth(request.getUrl()) || super.shouldOverrideUrlLoading(view, request); } /** * This method will inject polyfills to the auth javascript if the version is * below Lollipop. After Lollipop WebView is updated via the Play Store so the polyfills * are not needed. * * @param url The requests url * @return null if there request should not be altered or a new response * instance with polyfills. */ private WebResourceResponse shouldIntercept(String url) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return null; } if (url.matches(".*frameworks.*.js")) { InputStream in1 = null; InputStream in2 = null; Response response = null; try { response = new OkHttpClient.Builder().build() .newCall(new Request.Builder().get().url(url).build()).execute(); if (response.body() != null) { in1 = response.body().byteStream(); } in2 = getAssets().open("polyfills.js"); } catch (IOException e) { e.printStackTrace(); } if (response == null) { return null; } SequenceInputStream inputStream = new SequenceInputStream(in2, in1); return new WebResourceResponse("text/javascript", "utf-8", inputStream); } else { return null; } } private boolean overrideOAuth(Uri uri) { if (uri.getScheme().equals(getString(R.string.github_oauth_scheme))) { Intent data = new Intent(); data.setData(uri); setResult(RESULT_OK, data); finish(); return true; } return false; } }); setContentView(webView); }
From source file:project.cs.lisa.application.html.NetInfWebViewClient.java
@Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { Intent intent = new Intent(MainApplicationActivity.SEARCH_TRANSMISSION); MainApplicationActivity.getActivity().sendBroadcast(intent); if (!URLUtil.isHttpUrl(url)) { super.shouldInterceptRequest(view, url); return null; } else if (URLUtil.isHttpUrl(url)) { WebObject resource = null;//www.j a v a 2 s . c om File file = null; String contentType = null; String hash = null; // Get and publish resource try { // Search for url NetInfSearchResponse searchResponse = search(url); // Get url data hash = selectHash(searchResponse); NetInfRetrieveResponse retrieveResponse = retrieve(hash); file = retrieveResponse.getFile(); contentType = retrieveResponse.getContentType(); } catch (Exception e1) { Log.e(TAG, "Request for resource failed. Downloading from uplink."); resource = downloadResource(url); if (resource == null) { return null; } file = resource.getFile(); contentType = resource.getContentType(); hash = resource.getHash(); } // Publish try { if (shouldPublish()) { publish(file, new URL(url), hash, contentType); } } catch (MalformedURLException e1) { Log.e(TAG, "Malformed url. Can't publish file."); } // Creating the resource that will be used by the webview WebResourceResponse response = null; try { response = new WebResourceResponse(contentType, "base64", FileUtils.openInputStream(file)); } catch (IOException e) { Log.e("TAG", "Could not open file"); } System.gc(); return response; } else { Log.e(TAG, "Unexpected url while intercepting resources."); return super.shouldInterceptRequest(view, url); } }
From source file:com.polyvi.xface.view.XWebViewClient.java
@SuppressLint("Override") @TargetApi(11)//from ww w.java2 s . com public WebResourceResponse shouldInterceptRequest(WebView view, String url) { /** url????? */ XWhiteList whiteList = mWebAppView.getOwnerApp().getAppInfo().getWhiteList(); if ((url.startsWith("http://") || url.startsWith("https://")) && (null != whiteList && !whiteList.isUrlWhiteListed(url))) { return getWhitelistResponse(); } if (url.indexOf(XConstant.ASSERT_PROTACAL) == 0) { for (int i = 0; i < URL_PARAMS_TAG.length; i++) { if (url.contains(URL_PARAMS_TAG[i])) { String filePath = url.substring(XConstant.ASSERT_PROTACAL.length(), url.length()); filePath = filePath.substring(0, filePath.indexOf(URL_PARAMS_TAG[i])); try { InputStream is = mSystemContext.getContext().getAssets().open(filePath); WebResourceResponse wr = new WebResourceResponse("text/javascript", "utf-8", is); return wr; } catch (IOException e) { return null; } } } } return null; }
From source file:com.polyvi.xface.view.XWebViewClient.java
/** ????? */ @SuppressLint("NewApi") private WebResourceResponse getWhitelistResponse() { String empty = ""; ByteArrayInputStream data = new ByteArrayInputStream(empty.getBytes()); return new WebResourceResponse("text/plain", "UTF-8", data); }
From source file:com.mobicage.rogerthat.plugins.messaging.AttachmentViewerActivity.java
@SuppressLint({ "SetJavaScriptEnabled" }) protected void updateView(boolean isUpdate) { T.UI();/*from www . jav a 2s . c o m*/ if (!isUpdate && mGenerateThumbnail) { File thumbnail = new File(mFile.getAbsolutePath() + ".thumb"); if (!thumbnail.exists()) { boolean isImage = mContentType.toLowerCase(Locale.US).startsWith("image/"); boolean isVideo = !isImage && mContentType.toLowerCase(Locale.US).startsWith("video/"); try { // Try to generate a thumbnail mMessagingPlugin.createAttachmentThumbnail(mFile.getAbsolutePath(), isImage, isVideo); } catch (Exception e) { L.e("Failed to generate attachment thumbnail", e); } } } final String fileOnDisk = "file://" + mFile.getAbsolutePath(); if (mContentType.toLowerCase(Locale.US).startsWith("video/")) { MediaController mediacontroller = new MediaController(this); mediacontroller.setAnchorView(mVideoview); Uri video = Uri.parse(fileOnDisk); mVideoview.setMediaController(mediacontroller); mVideoview.setVideoURI(video); mVideoview.requestFocus(); mVideoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mVideoview.start(); } }); mVideoview.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { L.e("Could not play video, what " + what + ", extra " + extra + ", content_type " + mContentType + ", and url " + mDownloadUrl); AlertDialog.Builder builder = new AlertDialog.Builder(AttachmentViewerActivity.this); builder.setMessage(R.string.error_please_try_again); builder.setCancelable(true); builder.setTitle(null); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); finish(); } }); builder.setPositiveButton(R.string.rogerthat, new SafeDialogInterfaceOnClickListener() { @Override public void safeOnClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); builder.create().show(); return true; } }); } else if (CONTENT_TYPE_PDF.equalsIgnoreCase(mContentType)) { WebSettings settings = mWebview.getSettings(); settings.setJavaScriptEnabled(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { settings.setAllowUniversalAccessFromFileURLs(true); } mWebview.setWebViewClient(new WebViewClient() { @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (fileOnDisk.equals(url)) { return null; } L.d("404: Expected: '" + fileOnDisk + "'\n Received: '" + url + "'"); return new WebResourceResponse("text/plain", "UTF-8", null); } }); try { mWebview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + URLEncoder.encode(fileOnDisk, "UTF-8")); } catch (UnsupportedEncodingException uee) { L.bug(uee); } } else { WebSettings settings = mWebview.getSettings(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { settings.setAllowFileAccessFromFileURLs(true); } settings.setBuiltInZoomControls(true); settings.setLoadWithOverviewMode(true); settings.setUseWideViewPort(true); if (mContentType.toLowerCase(Locale.US).startsWith("image/")) { String html = "<html><head></head><body><img style=\"width: 100%;\" src=\"" + fileOnDisk + "\"></body></html>"; mWebview.loadDataWithBaseURL("", html, "text/html", "utf-8", ""); } else { mWebview.loadUrl(fileOnDisk); } } L.d("File on disk: " + fileOnDisk); }
From source file:org.apache.cordova.engine.crosswalk.XWalkCordovaWebViewClient.java
@Override public WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) { try {/*from www . j a v a2 s . c o m*/ // Check the against the white-list. if ((url.startsWith("http:") || url.startsWith("https:")) && !Config.isUrlWhiteListed(url)) { LOG.w(TAG, "URL blocked by whitelist: " + url); // Results in a 404. return new WebResourceResponse("text/plain", "UTF-8", null); } CordovaResourceApi resourceApi = appView.getResourceApi(); Uri origUri = Uri.parse(url); // Allow plugins to intercept WebView requests. Uri remappedUri = resourceApi.remapUri(origUri); if (!origUri.equals(remappedUri) || needsSpecialsInAssetUrlFix(origUri) || needsKitKatContentUrlFix(origUri)) { OpenForReadResult result = resourceApi.openForRead(remappedUri, true); return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream); } // If we don't need to special-case the request, let the browser load it. return null; } catch (IOException e) { if (!(e instanceof FileNotFoundException)) { LOG.e("IceCreamCordovaWebViewClient", "Error occurred while loading a file (returning a 404).", e); } // Results in a 404. return new WebResourceResponse("text/plain", "UTF-8", null); } }
From source file:com.mobicage.rogerthat.plugins.friends.ActionScreenActivity.java
@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface", "NewApi" }) @Override/*from ww w. j a v a 2 s. c o m*/ public void onCreate(Bundle savedInstanceState) { if (CloudConstants.isContentBrandingApp()) { super.setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen); } super.onCreate(savedInstanceState); setContentView(R.layout.action_screen); mBranding = (WebView) findViewById(R.id.branding); WebSettings brandingSettings = mBranding.getSettings(); brandingSettings.setJavaScriptEnabled(true); brandingSettings.setCacheMode(WebSettings.LOAD_DEFAULT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { brandingSettings.setAllowFileAccessFromFileURLs(true); } mBrandingHttp = (WebView) findViewById(R.id.branding_http); mBrandingHttp.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); WebSettings brandingSettingsHttp = mBrandingHttp.getSettings(); brandingSettingsHttp.setJavaScriptEnabled(true); brandingSettingsHttp.setCacheMode(WebSettings.LOAD_DEFAULT); if (CloudConstants.isContentBrandingApp()) { mSoundThread = new HandlerThread("rogerthat_actionscreenactivity_sound"); mSoundThread.start(); Looper looper = mSoundThread.getLooper(); mSoundHandler = new Handler(looper); int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA); if (cameraPermission == PackageManager.PERMISSION_GRANTED) { mQRCodeScanner = QRCodeScanner.getInstance(this); final LinearLayout previewHolder = (LinearLayout) findViewById(R.id.preview_view); previewHolder.addView(mQRCodeScanner.view); } mBranding.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { initFullScreenForContentBranding(); } }); mBrandingHttp.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { initFullScreenForContentBranding(); } }); } final View brandingHeader = findViewById(R.id.branding_header_container); final ImageView brandingHeaderClose = (ImageView) findViewById(R.id.branding_header_close); final TextView brandingHeaderText = (TextView) findViewById(R.id.branding_header_text); brandingHeaderClose .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text))); brandingHeaderClose.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.onResume(); } brandingHeader.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl("about:blank"); } }); final View brandingFooter = findViewById(R.id.branding_footer_container); if (CloudConstants.isContentBrandingApp()) { brandingHeaderClose.setVisibility(View.GONE); final ImageView brandingFooterClose = (ImageView) findViewById(R.id.branding_footer_close); final TextView brandingFooterText = (TextView) findViewById(R.id.branding_footer_text); brandingFooterText.setText(getString(R.string.back)); brandingFooterClose .setColorFilter(UIUtils.imageColorFilter(getResources().getColor(R.color.mc_homescreen_text))); brandingFooter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.onResume(); } brandingHeader.setVisibility(View.GONE); brandingFooter.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl("about:blank"); } }); } final RelativeLayout openPreview = (RelativeLayout) findViewById(R.id.preview_holder); openPreview.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQRCodeScanner != null) { mQRCodeScanner.previewHolderClicked(); } } }); mBranding.addJavascriptInterface(new JSInterface(this), "__rogerthat__"); mBranding.setWebChromeClient(new WebChromeClient() { @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { if (sourceID != null) { try { sourceID = new File(sourceID).getName(); } catch (Exception e) { L.d("Could not get fileName of sourceID: " + sourceID, e); } } if (mIsHtmlContent) { L.i("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message); } else { L.d("[BRANDING] " + sourceID + ":" + lineNumber + " | " + message); } } }); mBranding.setWebViewClient(new WebViewClient() { private boolean isExternalUrl(String url) { for (String regularExpression : mBrandingResult.externalUrlPatterns) { if (url.matches(regularExpression)) { return true; } } return false; } @SuppressLint("DefaultLocale") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { L.i("Branding is loading url: " + url); Uri uri = Uri.parse(url); String lowerCaseUrl = url.toLowerCase(); if (lowerCaseUrl.startsWith("tel:") || lowerCaseUrl.startsWith("mailto:") || isExternalUrl(url)) { Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; } else if (lowerCaseUrl.startsWith(POKE)) { String tag = url.substring(POKE.length()); poke(tag); return true; } else if (lowerCaseUrl.startsWith("http://") || lowerCaseUrl.startsWith("https://")) { if (mQRCodeScanner != null) { mQRCodeScanner.onPause(); } brandingHeaderText.setText(getString(R.string.loading)); brandingHeader.setVisibility(View.VISIBLE); if (CloudConstants.isContentBrandingApp()) { brandingFooter.setVisibility(View.VISIBLE); } mBranding.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.VISIBLE); mBrandingHttp.loadUrl(url); return true; } else { brandingHeader.setVisibility(View.GONE); brandingFooter.setVisibility(View.GONE); mBrandingHttp.setVisibility(View.GONE); mBranding.setVisibility(View.VISIBLE); } return false; } @Override public void onPageFinished(WebView view, String url) { L.i("onPageFinished " + url); if (!mInfoSet && mService != null && mIsHtmlContent) { Map<String, Object> info = mFriendsPlugin.getRogerthatUserAndServiceInfo(mServiceEmail, mServiceFriend); executeJS(true, "if (typeof rogerthat !== 'undefined') rogerthat._setInfo(%s)", JSONValue.toJSONString(info)); mInfoSet = true; } } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { L.i("Checking access to: '" + url + "'"); final URL parsedUrl; try { parsedUrl = new URL(url); } catch (MalformedURLException e) { L.d("Webview tried to load malformed URL"); return new WebResourceResponse("text/plain", "UTF-8", null); } if (!parsedUrl.getProtocol().equals("file")) { return null; } File urlPath = new File(parsedUrl.getPath()); if (urlPath.getAbsolutePath().startsWith(mBrandingResult.dir.getAbsolutePath())) { return null; } L.d("404: Webview tries to load outside its sandbox."); return new WebResourceResponse("text/plain", "UTF-8", null); } }); mBrandingHttp.setWebViewClient(new WebViewClient() { @SuppressLint("DefaultLocale") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { L.i("BrandingHttp is loading url: " + url); return false; } @Override public void onPageFinished(WebView view, String url) { brandingHeaderText.setText(view.getTitle()); L.i("onPageFinished " + url); } }); Intent intent = getIntent(); mBrandingKey = intent.getStringExtra(BRANDING_KEY); mServiceEmail = intent.getStringExtra(SERVICE_EMAIL); mItemTagHash = intent.getStringExtra(ITEM_TAG_HASH); mItemLabel = intent.getStringExtra(ITEM_LABEL); mItemCoords = intent.getLongArrayExtra(ITEM_COORDS); mRunInBackground = intent.getBooleanExtra(RUN_IN_BACKGROUND, true); }