Advertisement
Guest User

JSONException Treehouse

a guest
Jul 19th, 2014
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1.         @Override
  2.         protected String doInBackground(Object... arg0) {
  3.             int responseCode = -1;
  4.            
  5.             try {
  6.                 URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
  7.                 HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
  8.                 connection.connect();
  9.                
  10.                 responseCode = connection.getResponseCode();
  11.                 if (responseCode == HttpURLConnection.HTTP_OK) {
  12.                     InputStream inputStream = connection.getInputStream();
  13.                     Reader reader = new InputStreamReader(inputStream);
  14.                     int contentLength = connection.getContentLength();
  15.                     char[] charArray = new char[contentLength];
  16.                     reader.read(charArray);
  17.                     String responseData = new String(charArray);
  18.  
  19.                     JSONObject jsonResponse = new JSONObject(responseData);
  20.                     String status = jsonResponse.getString("status");
  21.                     Log.v(TAG, status);
  22.                     JSONArray jsonPosts = jsonResponse.getJSONArray("posts");
  23.                    
  24.                     for (int i = 0; i < jsonPosts.length(); i++) {
  25.                         JSONObject jsonPost = jsonPosts.getJSONObject(i);
  26.                         String title = jsonPost.getString("title");
  27.                         Log.v(TAG, "Post " + i + ": " + title);
  28.                     }
  29.                 }
  30.                 else {
  31.                     Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
  32.                 }
  33.             }
  34.             catch (MalformedURLException e) {
  35.                 Log.e(TAG, "Exception caught: ", e);
  36.             }
  37.             catch (IOException e) {
  38.                 Log.e(TAG, "Exception caught: ", e);       
  39.             }
  40.             catch (Exception e) {
  41.                 Log.e(TAG, "Exception caught: ", e);   
  42.             }
  43.             return "Code:" + responseCode;
  44.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement