在Android WebView中,我们常常会自定义一个WebViewClient并重写 shouldOverrideUrlLoading方法 来处理网页内的超链接事件。
但有时候我们会发现我们首次加载url也会进入到 shouldOverrideUrlLoading 方法中,这是因为我们的初始链接并不是网页记载成功后的真正链接,而是被系统重定向过的。所以在某些情况下就需要我们在加载网页前获取 url 的重定向地址。
/** * 获取重定向地址 * * @param path * @return * @throws Exception */ private String getRedirectUrl(String path) { String url = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(5000); url = conn.getHeaderField("Location"); conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } return url; }
这里需要注意 getRedirectUrl 方法是需要运行在子线程中的。
new Thread() { @Override public void run() { final String path = getRedirectUrl(uri.toString()); getActivity().runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl(path); } }); } }.start();}}.start();