Android: downloading a file from a password-protected website

I need to download some PDF files from a site where users must log in before they can download any files.

If the user has not visited the site, links to PDF files will be redirected to the login page.

I managed to post the user credentials on the login page and save the cookie from the response, and I tried to provide this cookie URLConnectionwhen trying to load, but I still get the login page instead of my pdf file.

Added

The UPDATE: .

Posting user credentials:

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write("username=" + username + "&password=" + password);
writer.flush();
writer.close();
os.close();

String result = HttpUtils.getResponseString(conn);
if (result.indexOf("Invalid") == -1) {
    String cookie = conn.getHeaderField("set-cookie");
    return cookie;
}

The cookie is then saved and used in the next code segment.

Attempt to download pdf:

URLConnection conn = url.openConnection();
conn.setRequestProperty("Cookie", _cookie);
conn.connect();
InputStream inStream = new BufferedInputStream(url.openStream(), 1024);
OutputStream outStream = new FileOutputStream(_pdfFile);
byte buffer[] = new byte[1024];
int count = 0;
while ((count = inStream.read(buffer)) != -1)
    outStream.write(buffer, 0, count);
outStream.flush();
outStream.close();
inStream.close();
+4

Source: https://habr.com/ru/post/1624501/


All Articles