I'm guessing that you're calling this code from the main-thread (within an Activity perhaps?), which isn't allowed in Android. Network-operations can't take place on the Main (or UI) thread.
To work around this, use an AsyncTask
and have a look at this: android.os.NetworkOnMainThreadException
This is an Android specific thing that you have to be aware of. The real problem here is the way you're handling your exception(s): By catching not a specific, but all possible exceptions (checked and unchecked), and then not printing at least the stack-trace, you have made it almost impossible to debug your code.
The problem with swallowing all exceptions that way, is that sometimes you get exceptions that you don't expect to get, in this case the NetworkOnMainThreadException
. You should actually want your application to crash in this case, otherwise you might never realize that there is a failure. While your code won't crash, it also won't do what you want, which is harder to fix (these kinds of errors are often not even detected for long times).
Some free advise:
- Be as specific as you can when catching exceptions. Make multiple
catch
-blocks and handle exceptions there. If you get an exception that you don't expect, something is up!
- If you can't recover from an exception, it's completely fine to crash the app and not just log it and continue as if nothing happened. This way, you'll actually learn that there is a possible crash scenario and you can prepare for that.
- Always print the stack-trace instead of just the message. The stack-trace contains much more detailed information, including the message if there is one (This makes your error even more confusing, since the message for the exception is set to
null
).
- You can wrap a checked-exception in a
RuntimeException
to make your App crash when something unrecoverable happens, but make sure to add the original Exception as the cause in the RuntimeException(String, Throwable)
-constructor! Otherwise, this information is lost!