0

Hi I am using the following code but I cannot get the iStream from the url. The url returns a JSON Array.

URL url = new URL(tomato_search);
URLConnection urlConnection = url.openConnection();
InputStream iStream = new BufferedInputStream(urlConnection.getInputStream());
readStream(iStream);
iStream.close();
ci_
  • 8,594
  • 10
  • 39
  • 63
charilaos13
  • 543
  • 2
  • 7
  • 19

1 Answers1

0

If you are using http to communicate, better to use HttpURLConnection.

JsonArray jsonArray;
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://www.example.com/endpoint").openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.connect();
InputStream is = httpsURLConnection.getInputStream();
try {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        while (br.readLine() != null) {
            sb.append(br.readLine()).append("\n");
        }
        br.close();

        jsonArray = new JSONArray(sb.toString());
    } catch (IOException | JSONException e) {
        jsonArray = null;
    }
xiaomi
  • 6,553
  • 3
  • 29
  • 34
  • I just want to get the inputstream return because then I am using the readstream(iStream) method to get the Json object like:{ JSONArray jarray=new JSONArray(in); for(int i=0; i – charilaos13 Sep 07 '15 at 10:03
  • I use this code to get data (json object/ array) from my server. I did a bad copy past sorry. Check again the code ;) – xiaomi Sep 07 '15 at 10:07
  • Sry for the questions but I am a bit confuse. Why do you use a String and the new line char to get the inputstream? and what is the Constants.DEBUG... for? – charilaos13 Sep 07 '15 at 11:50
  • Sorry I removed the debug line and the String line. So when you get the InputStream and because you are looking for a json format (usually a string), you will have to InputStreamReader to transform a stream of bytes to a stream of characters. Then you have the BufferedReader which will buffered lines. So from each line of this BufferedReader, you will build string and then use this string to build your JsonArray. – xiaomi Sep 07 '15 at 12:00
  • I am still getting an error at the httpURLConnection.connect(); method – charilaos13 Sep 07 '15 at 12:12
  • Can you post what log cat outputs ? connect sould give you an IOException. – xiaomi Sep 07 '15 at 12:16
  • 09-07 12:23:55.090 3024-3038/? W/EGL_emulation﹕ eglSurfaceAttrib not implemented 09-07 12:23:55.090 3024-3038/? W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xabee9380, error=EGL_SUCCESS – charilaos13 Sep 07 '15 at 12:24
  • Seems that the problem does not come from an IOException :/ – xiaomi Sep 07 '15 at 12:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89000/discussion-between-charilaos13-and-xiaomi). – charilaos13 Sep 07 '15 at 12:27