Setting a request body in Android's DownloadManager?
Asked Answered
D

1

11

For the next step of my application, I need to add download functionality. The user chooses what they want to download and could select anything from 1 file to thousands of them if they could be bothered to select that many.

I want to use Android's built in DownloadManager to provide this downloading functionality, but unfortunately I cannot see how I could implement it for my scenario.

In order for the target server to authorize the download, I need to send some JSON along in the request body. Like this, if I was doing it manually:

DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(rawData);
output.flush();

Where rawData is the JSON string. The request body is always set to POST.

I can't seem to find any way to add this JSON string to the DownloadManager, and until I can do that, the server will always reject the download.

The only other solution that I can think of, which I desperately want to avoid, is writing a PHP script on my server to take some GET parameters, generate the JSON and then redirect the request.

Does anybody know of a way that I can send my JSON data along with the DownloadManager? Each file that I'm downloading needs its own, unique, JSON string.

Dreamland answered 24/5, 2012 at 17:27 Comment(0)
E
0

you cannot do that in Android's Download manager, see Download Manager Issue, I had a similar requirement and I ended up Using HttpClient (Xamarin).

Sample Code-

using(var httpClient = new HttpClient()) {
  using(var request = new HttpRequestMessage(new HttpMethod("POST"), URL)) {
   request.Headers.TryAddWithoutValidation("User-Agent", userAgent);
   request.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
   request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.5");
   request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
   request.Headers.TryAddWithoutValidation("Referer",RefererURL);
   request.Content = new StringContent("YOUR_REQUEST_BODY_HERE");
   request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

   var responser = await httpClient.SendAsync(request);
   return responser;
  }
Excitation answered 28/5, 2020 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.