More often than not when developing a custom browser in android, we face many hurdles at the time of downloading the files. On this blog we will look into 2 major things that Developers need to consider while developing their browser app.
- Adding Cookies to Android’s DownloadManager requests.
When downloading a file from a website where users have to login to be able to access/download the file, we might face access denied error when processing the download. To fix this we need to add cookies from that particular url in the Download Requests.
If Android’s own Download manager is used to initiate download the below will the code :
android.app.DownloadManager.Request mRequest; … String mStringCookieForUrl = “”; mStringCookieForUrl = CookieManager.getInstance().getCookie(url); mRequest.addRequestHeader(“cookie”,mStringCookieForUrl); … |
If HttpURLConnection is being used below code can be used :
final HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();… String mStringCookieForUrl = “”; mStringCookieForUrl = CookieManager.getInstance().getCookie(url); mHttpURLConnection.addRequestProperty(“Cookie”,mStringCookieForUrl);… |
In the code above in the download request, we need to add the cookie string of that specific url. To do this we have to use CookieManager.getInstance().getCookie(url) inbuilt method to retrieve the cookie string.
If you don’t want to use CookieManager class, you can retrieve the cookie string using the following code too :
String mStringCookieForUrl = “”; mStringCookieForUrl = mWebView.getCookieForUrl(url); |
2. Adding User-Agent at the time of download :
When downloading a file, sometimes we face errors when downloading and in the output stream we get html content instead of the actual file. So in result, User will get a corrupted file. This issue happens because some websites are designed in such a way that it only supports only some types of Browsers like Chrome, FireFox etc. So even if your browser is supported by the site via user agent, in the request header you need to specify the user-agent field to make it work
To do this we need to retrieve our user agent from the webview at the time of making the download request.
final HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();… String mUserAgent = mWebView.getSettings().getUserAgentString();mHttpURLConnection.addRequestProperty(“User-Agent”,mUserAgent);… |
To add custom user agent, you can just add user agent string in the addRequestProperty method of HttpURLConnection object like below :
mHttpURLConnection.addRequestProperty(“User-Agent”,<Custom-User-Agent>);