HttpURLConnection.getInputStream返回null android

时间:2016-01-26 10:15:23

标签: android

在我的应用程序中,我试图下载音频文件但是使用HttpUrlConnection的getInputStream()方法但getInputStream()方法返回null。我不知道它为什么会发生。有什么帮助?下面是代码我我正在使用

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;
            }
        }

我在浏览器中使用上面的URL它流媒体很好,但在应用程序中它无法正常工作。

3 个答案:

答案 0 :(得分:2)

如果这是您的实际代码,那么您会遇到一个简单的错误:

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

您的if导致inputStream未被分配,或仅在出错时分配。

答案 1 :(得分:1)

在使用httpURLConnection.connect()(和httpURLConnection.getInputStream())之前,您忘记致电httpURLConnection.getResponseCode()

答案 2 :(得分:0)

我认为您应该检查响应代码是否正确而不是否定