How can I use Android to download a session/cookie

2019-06-17 10:01发布

I'm trying to download a file using webView from file hosts (like zippyshare.com). Problem is, I can't use intents to open a browser, or reroute it through DownloadManager, since it's session/cookie based, and launching those methods redirects the zip file into the original html file to re-downlad.

I've tried:

Uri source = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(source);

String cookie = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("Set-Cookie", cookie);
request.addRequestHeader("User-Agent", view.getSettings().getUserAgentString());
request.addRequestHeader("Accept", "text/html, application/xhtml+xml, *" + "/" + "*");
request.addRequestHeader("Accept-Language", "en-US,en;q=0.7,he;q=0.3");
request.addRequestHeader("Referer", url);

// Use the same file name for the destination
final File destinationDir = new File (Environment.getExternalStorageDirectory(), cordova.getActivity().getPackageName());

if (!destinationDir.exists()) {
    destinationDir.mkdir(); // Don't forget to make the directory if it's not there
}

File destinationFile = new File (destinationDir, source.getLastPathSegment());
Log.e("FILEPOSITION", Uri.fromFile(destinationFile).toString());
request.setDestinationUri(Uri.fromFile(destinationFile));
// Add it to the manager
manager.enqueue(request);

and:

Bundle bundle = new Bundle();

String cookie = CookieManager.getInstance().getCookie(url);
bundle.putString("cookie", cookie);
bundle.putString("User-Agent", view.getSettings().getUserAgentString());

Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse(url));
intent.putExtra(Browser.EXTRA_HEADERS, bundle);
cordova.getActivity().startActivity(intent);

to try to preserve the cookie, and while I see the headers are sent just fine, it still redirects to the html link, which leads me to believe it's session based.

Is there a way of downloading a file in that manner?

1条回答
Rolldiameter
2楼-- · 2019-06-17 10:52

I was dealing with the same problem and I managed to get your first solution working, only with a slight change. Just replace Set-Cookie width Cookie:

request.addRequestHeader("Cookie", cookie);

Btw. session based means that the auth data are not stored in cookies but on server side, identified by a key, which IS stored in cookies. So it actually doesn't matter whether it's session based or not, cookies are used in both cases.

I've also tried the second solution (it's simpler) but from what I've read it seems that Browser.EXTRA_HEADERS is supported only by the default Android browser. So if the user has a different browser in his device it won't work.

This is an old question but I hope it will help someone.

查看更多
登录 后发表回答