Thursday, June 16, 2011

How to : Set Android WebView HTTP Referrer programmatically

In Android, you may use the webview.LoadData to show html. using the following code,

public class WebViewTestActivity extends Activity {

WebView wv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainbrownser);
wv = (WebView) findViewById(R.id.wv);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadData(
"<img src='http://images.google.com/intl/en_ALL/images/logos/images_logo_lg.gif'>",
"text/html", "UTF-8");
}

}


When you run the app, you can see the google logo there,
image

however, if you try to access some image whose server will check the referrer, you will be in trouble to viewing the image.
by default, the webview doesn’t setup the referrer when fetching html resouces,
image

I searched a lot, there is no explicit way to setup the referrer . after checking the webview source code, here is the trick to setup the referrer, using the loaddatawithbaseurl, the baseurl will be the referrer picked by webview

imageCode,

wv.loadDataWithBaseURL("http://wwwgoogle.com/myreferrer",
"<img src='http://images.google.com/intl/en_ALL/images/logos/images_logo_lg.gif?a=1'>",
"text/html", "UTF-8","");


Hope it helps,

2 comments:

Field.Kao said...

It is helpful,Thank you!

Venu Chowdary said...
This comment has been removed by the author.
 
Locations of visitors to this page