1. 程式人生 > >利用執行緒池實現Android客戶端的http網路資料請求工具類

利用執行緒池實現Android客戶端的http網路資料請求工具類

該工具類值只實現了HTTP的get方法,參考get方法可輕鬆實現post、put、delete等方法,下面是get方法的實現

public class SimpleHttpClient {
	
	private static final String TAG = SimpleHttpClient.class.getSimpleName();

	public static int POOL_SIZE = 8;
	
	private static ExecutorService sExecutorService;
	
	private static int READ_TIME_OUT = 10 * 1000;
	
	private static int CONNECTE_TIME_OUT = 10 * 1000;
	
	private static final String ENCODE = "UTF-8";
	
	static {
		sExecutorService = Executors.newFixedThreadPool(POOL_SIZE);
	}
	
	public interface HttpCallback <T> {
		public  void onSuccess(T response);
		public  void onError(T error);
	}
	
	public static void doGet(String url,final HttpCallback<String> callback) {
		final String _url = url;
		sExecutorService.submit(new Runnable() {
			
			@Override
			public void run() {
				URL url = null;
				try {
					url = new URL(_url);
				} catch (MalformedURLException e) {
					e.printStackTrace();
					callback.onError(e.getMessage());
					return;
				}
				BufferedReader bufferedReader  = null;
				StringBuffer response = new StringBuffer();
				HttpURLConnection urlConnection = null;
				try {
					urlConnection = (HttpURLConnection) url.openConnection();
					urlConnection.setDoInput(true);
					urlConnection.setReadTimeout(READ_TIME_OUT);
					urlConnection.setConnectTimeout(CONNECTE_TIME_OUT);
					urlConnection.setRequestMethod("GET");
					urlConnection.setUseCaches(false);
					urlConnection.setRequestProperty("connection", "close");
					urlConnection.connect();
					int code = urlConnection.getResponseCode();
					if (code >= 200 && code < 400) {
						bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),ENCODE));
						String line = null;
						while ((line = bufferedReader.readLine()) != null) {
							response.append(line);
						}
						callback.onSuccess(response.toString());
					} else {
						bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream(),ENCODE));
						String line = null;
						while ((line = bufferedReader.readLine()) != null) {
							response.append(line);
						}
						callback.onError(response.toString());
					}
				}catch (SocketTimeoutException e) {
					e.printStackTrace();
					callback.onError(e.getMessage());
				} catch (IOException e) {
					e.printStackTrace();
					callback.onError(e.getMessage());
				} finally {
					if (bufferedReader != null) {
						try {
							bufferedReader.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
	}
}

測試:
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void test(View view) {
    	String url = "http://www.weather.com.cn/adat/sk/101010100.html";
    	SimpleHttpClient.doGet(url, new HttpCallback<String>() {
			
			@Override
			public void onSuccess(String respose) {
				System.out.println("sucess:" + respose);
			}
			
			@Override
			public void onError(String error) {
				System.out.println("error:" + error);
			}
		});
    }

}
<pre name="code" class="java"><strong>佈局檔案:</strong>

<strong></strong><pre name="code" class="html"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.httpdemos.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="132dp"
        android:layout_toRightOf="@+id/textView1"
        android:onClick="test"
        android:text="Button" />

</RelativeLayout>
許可權:
 <uses-permission android:name="android.permission.INTERNET" />

測試結果: