1

I was first using HttpURLConnection with my first test. Now I would like to also support https, but it doesn't work. I've been at it all day and so far nothing. Most of the past problems have been related to certificate issues. Weird thing is in my case it downloads the file, but its either corrupted (if its a simple file), or the zips contents are missing (empty). I will post my code to see if maybe I am doing something wrong.

try{
    URL url = new URL(stuffs[0]);//<-actual url I am searching https://...
    String fileName = stuffs[1];
    String optionalFilePath = stuffs[2] == null ? null : stuffs[2];
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(20000);
    connection.connect();
        if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            checkErrorCode(connection.getResponseCode());
            return false;
        }
    InputStream in = new BufferedInputStream(connection.getInputStream());
    FileOutputStream out = null;

        if(optionalFilePath == null)
            out = new FileOutputStream(PATH +"/"+fileName);
        else {
            File newDir = new File(PATH+optionalFilePath);
            newDir.mkdirs();
            out = new FileOutputStream(PATH + (optionalFilePath==null?"":optionalFilePath) +"/"+fileName);
            }

    byte[] buffer = new byte[1024];
    int count;
    while((count = in.read(buffer)) != -1){
        out.write(buffer, 0, count);
        }

    out.flush();
    out.close();
    in.close();
    }

Upon further debugging, I found out the content length is -1. So I guess it makes sense why the zip is empty. Now I am not too sure why it returns -1. I download it on a web browser correctly. So I know it exists.

B770
  • 1,272
  • 3
  • 17
  • 34
Andy
  • 10,553
  • 21
  • 75
  • 125

2 Answers2

0

To Download file via https You should accept https certificate from application Trusting all certificates using HttpClient over HTTPS And https file download in android causing exception

For Downlod zip or any check this out Download a file with Android, and showing the progress in a ProgressDialog

Community
  • 1
  • 1
UdayaLakmal
  • 4,035
  • 4
  • 29
  • 40
0

I believe the answer is that you are calling connect().

URL url = new URL(stuffs[0]);//<-actual url I am searching https://...
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(20000);
connection.connect();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
    checkErrorCode(connection.getResponseCode());
    return false;
}
InputStream in = new BufferedInputStream(connection.getInputStream());

Try not calling connection.connect, and moving the response code check after the line that calls connection.getInputStream().

K Boden
  • 626
  • 4
  • 6