0

For some reason, only "[" is being returned as the result of this call to this URI. When I browse to the URL, it shows all of the JSON data correctly. I am getting a "200" response so this is not due to any sort of authentication issue, as it doesn't require any credentials and I am just trying to directly retrieve and parse the JSON data.

public class QueryManager extends AsyncTask {
    private static final String DEBUG_TAG = "QueryManager";

    @Override
    protected ArrayList<Recipe> doInBackground(Object... params) {
        try {
            return searchIMDB((String) params[0]);
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(Object result) {
    };

    public ArrayList<Recipe> searchIMDB(String query) throws IOException {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json");
        //create URI
        URL url = new URL(stringBuilder.toString());

        InputStream stream = null;
        try {
            // Establish a connection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.addRequestProperty("Accept", "application/json");
            conn.setDoInput(true);
            conn.connect();

            int responseCode = conn.getResponseCode();
            Log.d(DEBUG_TAG, "The response code is: " + responseCode + " " + conn.getResponseMessage());

            stream = conn.getInputStream();
            return parseResult(stringify(stream));
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    private ArrayList<Recipe> parseResult(String result) {
        String streamAsString = result;
        ArrayList<Recipe> results = new ArrayList<Recipe>();
        try {
            JSONArray array = new JSONArray(streamAsString);
            //JSONArray array = (JSONArray) jsonObject.get("results");
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonMovieObject = array.getJSONObject(i);

                Recipe newRecipe = new Recipe();

                newRecipe.name = jsonMovieObject.getString("name");
                newRecipe.id = jsonMovieObject.getInt("id");

                JSONArray ingredients = (JSONArray) jsonMovieObject.get("ingredients");

                for(int j = 0; j < ingredients.length(); j++) {
                    JSONObject ingredientObject = ingredients.getJSONObject(j);
                    Ingredient ingredient = new Ingredient();

                    ingredient.ingredientName = ingredientObject.getString("ingredient");
                    ingredient.quantity = ingredientObject.getDouble("quantity");
                    ingredient.measure = ingredientObject.getString("measure");

                    newRecipe.ingredientList.add(ingredient);
                }

            }
        } catch (JSONException e) {
            System.err.println(e);
            Log.d(DEBUG_TAG, "Error parsing JSON. String was: " + streamAsString);
        }
        return results;
    }

    public String stringify(InputStream stream) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream);
        BufferedReader bufferedReader = new BufferedReader(reader);
        return bufferedReader.readLine();
    }
}
J.J.
  • 1,128
  • 2
  • 23
  • 62
  • Your `stringify` function looks like it returns only the first line from the `bufferedReader`. Have you tried iterating through all of the lines? – Jacob Aug 06 '18 at 15:29

2 Answers2

2

The JSON you get is beautified (i.e. has newlines and probably indentation).
However, in your stringify function you only read and return the first line of the response:

return bufferedReader.readLine();

See here for a list of possible solutions to read the entire InputStream to a String.
For example:

ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
    result.write(buffer, 0, length);
}
return result.toString("UTF-8");
RobCo
  • 6,240
  • 2
  • 19
  • 26
1

This is similar to what I was talking about in my comments:

public String stringify(InputStream stream) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream);
    BufferedReader bufferedReader = new BufferedReader(reader);
    StringBuilder results = new StringBuilder();
    try {
        String line;
        while ((line = BufferedReader.readLine()) != null) {
            results.append(line);
            results.append('\n');
        }
    } finally {
        try {
            bufferedReader.close();
        } catch (IOException | NullPointerException e) {
            e.printStackTrace();
        }
    }
    return results.toString();
}
Jacob
  • 299
  • 1
  • 18