Posts Tagged 'HttpURLConnection getInputStream FileNotFoundException problem android java'

HttpURLConnection getInputStream FileNotFoundException

Hello Android/Java coders!

So I recently got some weird errors when doing http requests in my Android game Hamster Climb. I was trying to get the input stream from a HttpURLConnection but kept getting a FileNotFoundException even tho the URL worked perfectly in my desktop browser. Here’s an example, without error catching stuff, of how the code could look like:

String user = getUser();
String url = "" + user;
URL u = new URL(url);

HttpURLConnection c = (HttpURLConnection) u.openConnection();

InputStream is = c.getInputStream();

The problem was that at the last line the call to getInputStream generated a FileNotFoundException. I printed the URL that was used and tried it in the browser. Worked prefectly.

I managed to solve it tho. The problem was that even tho creating a URL object with the built url string works, the url might be broken. For example, if user is “Some guy” the url will contain a space which is not valid. Browsers solve this by automatically replacing the space with %20 which is what my browser did.

To solve this in code you use the URLEncoder class’ static method encode. This method takes a string and encodes it to a string that is ok to put in a URL. So replacing

String url = "" + user;


String url = ""
+ URLEncoder.encode(user, "UTF-8");

solves the problem when user contains illegal URL characters.

Hope this helps someone out there getting weird errors. 🙂

I am a technology interested programmer. I live and work in Uppsala, Sweden after moving here to study Engineering Physics at Uppsala University.

❤️ cats