Search code examples
javainputstream

UrlConnection.getInputStream() returns an exception that is null in Java


I have the following java code

try {
    String u = "http://webapi.com/demo.zip";
    URL url = new URL(u);
    URLConnection ucon = url.openConnection();
    InputStream is = ucon.getInputStream();
}
catch (Exception e) {
    Log.d('downloaderror', e.getMessage());
}

But for some reason, the InputStream is = ucon.getInputStream() causes an error and the catch block is fired. And when the catch block is fired, the value of e is null.

Does anyone konw what is wrong with my ucon.getInputStream() ? I know for a fact that http://webapi.com/demo.zip exists, because I'm able to download the file from my web browser.

EDIT Here's the stack trace on ucon.getInputstream()

java.lang.Exception
            at com.example.instantramenz.samplewebview.MainActivity$1.onClick(MainActivity.java:94)
            at android.view.View.performClick(View.java:4633)
            at android.view.View$PerformClick.run(View.java:19270)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

Solution

  • i fixed the problem by putting this line of code before downloading the file:

                android.os.StrictMode.ThreadPolicy policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll().build();
                android.os.StrictMode.setThreadPolicy(policy);