Abdul Waheed
Abdul Waheed

Reputation: 4678

HttpURLConnection.getInputStream returning null android

In my application I am trying to download audio file but using HttpUrlConnection 's getInputStream() method but getInputStream() method returning null.I don't have any idea why it is happening.Any help?Below is the code I am using

URL downloadURL = null;
    HttpURLConnection httpURLConnection = null;
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    File file = null;
    try {
        downloadURL = new URL("http://thelearningapps.com/admin/userfiles/Rhymes/Arabic/The_Wheels_On_The_Bus_Arabic.mp3");
        httpURLConnection = (HttpURLConnection) downloadURL.openConnection();
        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK)
            //return;
        inputStream = httpURLConnection.getInputStream();
        file = AppUtility.getInternalDirectoryForRhymes(this, rhymeName);
        fileOutputStream = new FileOutputStream(file);
        int read = -1;
        long totalRead =0 ;
        int totalLength = httpURLConnection.getContentLength();
        byte [] buffer = new byte[1024];
        RhymesActivity.getInstance().registerMyReceiver();
        while ((read = inputStream.read(buffer)) != -1) {
            totalRead += read;
            fileOutputStream.write(buffer, 0, read);
            sendMyBroadCast(totalRead, totalLength, rhymeName);
            if (progressbarDetails != null) {
                progressbarDetails.isDownloading = true;
                progressbarDetails.rhymeName = rhymeName;
            }
        }

I am using above URL in browser it is streaming fine but in application it is not working.

Upvotes: 0

Views: 1757

Answers (3)

christoandrew
christoandrew

Reputation: 437

I think you are supposed to checking if the response code is ok not the negative

Upvotes: 0

marcinj
marcinj

Reputation: 50026

If that is your actual code then you have a simple error:

    if (responseCode != HttpURLConnection.HTTP_OK)
        //return;
    inputStream = httpURLConnection.getInputStream();

your if is causing inputStream to not being assigned, or beeing assigned only on error.

Upvotes: 2

Daniel Zolnai
Daniel Zolnai

Reputation: 16920

You forgot calling httpURLConnection.connect() before using httpURLConnection.getInputStream() (and httpURLConnection.getResponseCode()).

Upvotes: 1

Related Questions