Advertisement
Guest User

Android Blog Reader "GetBlogPosts" class

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