IO exception reading json with inputStream

I made a php application at the following url: http://localhost/index.php/registration/returnItemJson to return this valid json:

{"name":"test","price":30,"description":"is this working"}

In my android studio app, I am trying to read it with this:

URL url = new URL(strings[0]);

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        int response = connection.getResponseCode();
        Log.d("TAG", "Response code "+response);
        StringBuilder result = new StringBuilder();

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line;
        while(null != (line = reader.readLine())){
            result.append(line).append("\n");
        }

But I am getting an IO exception by connection.GetInputStream(). It works ok when I do this with some other url that returns json, but not with localhost.

2 answers

  • answered 2018-01-11 19:40 OjamaYellow

    Thanks to Kidus for solution, I just had to replace localhost with 10.0.2.2 because I use emulator.

  • answered 2018-01-11 19:40 Kidus

    Use 10.0.2.2 instead to access your local host. Read more here