編輯:Android 開發實例
當你點擊一個超連結進行跳轉時,WebView 會自動把當前網址作為 Referer 送給伺服器。因此不少站點會依 Referer 是否正確來攔截盜鏈。這也解釋了為什麼直接輸入某個網路位址常常打不開——缺少 Referer 就被擋掉了。
解法很直覺:載入時自行補上一個 Referer 標頭。
從 Android 2.2(API 8)開始,WebView 多了一個重載的 loadUrl,正是為了滿足「載入網頁的同時送出額外 HTTP 標頭」的需求。
public void loadUrl (String url, Map<String, String> additionalHttpHeaders) Added in API level 8 Loads the given URL with the specified additional HTTP headers. Parameters url — the URL of the resource to load additionalHttpHeaders — the additional headers to be used in the HTTP request for this URL, specified as a map from name to value. Note that if this map contains any of the headers that are set by default by this WebView, such as those controlling caching, accept types or the User-Agent, their values may be overriden by this WebView's defaults.
最後那段提醒值得注意:快取、Accept、User-Agent 這類由 WebView 預設設定的標頭,即使你傳了也可能被系統的值覆蓋。
public void testLoadURLWithHTTPHeaders() {
final String url = "https://jb51.net";
WebView webView = new WebView(getActivity());
Map<String,String> extraHeaders = new HashMap<String, String>();
extraHeaders.put("Referer", "https://www.google.com");
webView.loadUrl(url, extraHeaders);
}
同样的手法也能用在其他自訂標頭上,例如與後端約定好的版本識別或簽章欄位。提醒一下:Referer 這類標頭的偽造在安全上是有爭議的,正式專案中建議與後端協商改用 Token 或簽章驗證,而不要單純依賴 Referer。
ListView 動態修改字體大小的實例講解
本文實現一個小效果:點擊列表中某一項,該項的文字變大。核心思路只有兩個方法——自定義 Adapter 的 getView() 負責渲染,setOnItemClickLis
Android ApiDemo 系列四:自訂 Dialog 主題
在 Android 中,Activity 的外觀可以透過 Theme 調整。ApiDemo 的 Custom Dialog 範例將一個 Activity 套用自訂主題,使
Android LayoutInflater 的使用介紹
LayoutInflater 常用來將 XML 布局實例化成 View 物件。它與 findViewById 不同,後者是用來查找已經存在的控制項,而前者則是把布局檔案轉
手把手做 Android 登入頁:表單、驗證與錯誤嘗試的處理
登入畫面是許多 App 的第一道門。使用者要嘛成功進入,要嘛被擋在門外——而這中間的體驗細節,往往決定了對這個 App 的第一印象。本文從版面配置寫到程式邏輯,做出一個具