Java tutorial
/* * HNReader for Android, with preloading. * You can preload the content of HN Links and read the articles + comments when you're offline. * @author Vadim Kr. * @copyright (c) 2013 bndr * @license http://creativecommons.org/licenses/by-sa/3.0/legalcode */ package com.example.hnreader; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * An Async thread for downloading the content */ public class Download extends AsyncTask<String, Void, String> { protected Context context; private ProgressDialog Dialog; /** * Constructor * @param context */ public Download(Context context) { this.context = context; } @Override protected String doInBackground(String... url) { String s = getPage(url[0]); return s; } @Override protected void onPostExecute(String result) { } @Override protected void onPreExecute() { } /** * Make Http request to the url and return webpage as string; * * @param url * @return */ private String getPage(String url) { HttpParams httpParameters = new BasicHttpParams(); int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setTcpNoDelay(httpParameters, true); HttpResponse response; StringBuilder str = new StringBuilder(); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet(url); try { response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { str.append(line); } in.close(); } catch (Exception e) { return ""; } return str.toString(); } }