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();
}
}