Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private class GetBlogPostsTask extends AsyncTask<Object, Void, String> {
- @Override
- protected String doInBackground(Object[] objects) {
- int responseCode = -1;
- try {
- URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
- HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
- connection.connect();
- responseCode = connection.getResponseCode();
- if (responseCode == HttpsURLConnection.HTTP_OK) {
- InputStream inputStream = connection.getInputStream();
- Reader reader = new InputStreamReader(inputStream);
- int contentLength = connection.getContentLength();
- char[] charArray = new char[contentLength];
- reader.read(charArray);
- String responseData = new String(charArray);
- JSONObject jsonResponse = new JSONObject(responseData);
- String status = jsonResponse.getString("status");
- Log.v(TAG, status);
- JSONArray jsonPosts = jsonResponse.getJSONArray("posts");
- for (int i = 0; i < jsonPosts.length(); i++){
- JSONObject jsonPost = jsonPosts.getJSONObject(i);
- String title = jsonPost.getString("title");
- Log.v(TAG, "Post " + i + ": " + title);
- }
- }
- else {
- Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
- }
- }
- catch (MalformedURLException e){
- Log.e(TAG, "Exception caught: ", e);
- }
- catch (IOException e){
- Log.e(TAG, "Exception caught: ", e);
- }
- catch (Exception e){
- Log.e(TAG, "Exception caught: ", e);
- }
- return "Code: " + responseCode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement