天天看點

網絡請求架構----AsyncHttpClient的get,post和圖檔上傳伺服器

async-http-client庫是一個基于回調函數的Http異步通信用戶端Android元件,是在Apache的HttpClient庫的基礎上開發建構而成的。

Eclipse使用:導入android-async-http-1.4.4.jar包http://download.csdn.net/detail/dickyqie/9662215

AndroidStudio: gradle中引入compile'com.loopj.android:android-async-http:1.4.8'

功能特色

  • 利用版4.3.6上遊HttpClient代替Android提供defaulthttpclient
  • 相容AndroidAPI 23高
  • 做異步HTTP請求處理的響應匿名回調
  • HTTP請求發生UI線程之外
  • 請求使用線程池限制并發資源使用情況
  • get /後參數生成器( RequestParams )
  • 多檔案上傳沒有額外的第三方庫
  • JSON上傳流沒有額外的圖書館
  • 處理循環和相對重定向
  • 小的開銷給你的應用程式隻90kb一切
  • 自動智能請求重試次數品質不一的移動連接配接優化
  • 自動gzip響應解碼速度超快的請求支援
  • 二進制協定通信

    binaryhttpresponsehandler

  • 内置的響應分析JSON與

    jsonhttpresponsehandler

  • 節能反應直接進入檔案

    fileasynchttpresponsehandler

  • 大的持久性Cookie,儲存cookie到你的應用程式的SharedPreferences
  • 傑克遜JSON內建,gson或其他JSON序列化庫(德)

    basejsonhttpresponsehandler

  • 與SAX解析器支援

    saxasynchttpresponsehandler

  • 語言和内容編碼的支援,不僅僅是UTF-8

    效果圖:

    網絡請求架構----AsyncHttpClient的get,post和圖檔上傳伺服器
    案例如下:
public class MainActivity extends Activity implements OnClickListener {

	public static AsyncHttpClient mHttpc = new AsyncHttpClient();

	private TextView mTextView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_asynchttpclict);
		initView();
	}

	private void initView() {
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.btn3).setOnClickListener(this);
		findViewById(R.id.btn4).setOnClickListener(this);
		mTextView=(TextView) findViewById(R.id.Text);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn1:
			showHttpGet1();
			break;
		case R.id.btn2:
			showHttpGet2("https://www.baidu.com");
			break;
		case R.id.btn3:
			showHttpGet3();
			break;
		case R.id.btn4:
			showHttpPost();
			break;
		case R.id.btn5:
			
		case R.id.btn6:
			
		default:
			break;
		}

	}

	private void showHttpGet1() {
		AsyncHttpClient client = new AsyncHttpClient();
		client.get("https://www.baidu.com", new AsyncHttpResponseHandler() {
			@Override
			public void onStart() { // 請求啟動 請求前
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) { // 請求成功
				StringBuffer result = new StringBuffer("");
				int length = responseBody.length;
				for (int i = 0; i < length; i++) {
					result.append((char) (responseBody[i] & 0xff));
				}
				Toast.makeText(MainActivity.this, "結果:" + result.toString(), 2)
						.show();
				mTextView.setText("結果:" +result.toString());
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) // 請求失敗
			{

			}

			public void onRetry() { // 重試

			}

			@Override
			public void onProgress(int bytesWritten, int totalSize) { // 請求進度

			}

			@Override
			public void onFinish() { // 請求完成

			}
		});
	}

	public void showHttpGet2(String uri) {
		mHttpc.get(uri, null, new AsyncHttpResponseHandler() { // 請求失敗
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1,
							byte[] responseBody) {
						StringBuffer result = new StringBuffer("");
						int length = responseBody.length;
						for (int i = 0; i < length; i++) {
							result.append((char) (responseBody[i] & 0xff));
						}
						Toast.makeText(MainActivity.this,
								"結果:" + result.toString(), 2).show();
						mTextView.setText("結果:" +result.toString());
					}
				});
	}

	private void showHttpGet3() {
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("q", "test");
		params.put("showapi_appid", "11548");
		// 目前時間
		params.put("showapi_timestamp", "20160511151954");
		params.put("showapi_sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
		client.get("https://route.showapi.com/32-9", params,
				new TextHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String response) {
						Toast.makeText(MainActivity.this,
								"結果:" + response.toString(), 2).show();
						mTextView.setText("結果:" +response.toString());
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseBody, Throwable error) {
						Log.i("ERROR", error.toString());
					}
				});
	}

	/*
	 * 獲得字元串
	 */
	public void showHttpPost() {
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("q", "test");
		params.put("showapi_appid", "11548");
		// 目前時間
		params.put("showapi_timestamp", "20160511151954");
		params.put("showapi_sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
		client.post("https://route.showapi.com/32-9", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1,
							byte[] responseBody, Throwable arg3) {

					}

					@Override
					public void onSuccess(int arg0, Header[] arg1,
							byte[] responseBody) {
						StringBuffer result = new StringBuffer("");
						int length = responseBody.length;
						for (int i = 0; i < length; i++) {
							result.append((char) (responseBody[i] & 0xff));
						}
						Toast.makeText(MainActivity.this,
								"結果:" + result.toString(), 2).show();
						mTextView.setText("結果:" +result.toString());
					}
				});

	}

	

	/**
	 * 上傳單個檔案
	 */
	private void showFile() {
		File myFile = new File("filePath");// filePath--->檔案路徑
		RequestParams params = new RequestParams();
		try {
			params.put("time", "20160511151954");
			params.put("sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
			params.put("filename", myFile);
			AsyncHttpClient client = new AsyncHttpClient();
			client.post("url", params, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {

				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

				}
			});
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	/***
	 * 多個檔案上傳
	 * 
	 * @param sendFilesPath
	 */
	public void uploadFile(ArrayList<String> sendFilesPath) {
		if (sendFilesPath.size() == 0)
			return;

		String strUploadFile = "";
		AsyncHttpClient client = new AsyncHttpClient();
		client.setURLEncodingEnabled(false);

		RequestParams params = new RequestParams();
		params.put("time", "20160511151954");
		params.put("sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
		// 批量上傳
		for (int i = 0; i < sendFilesPath.size(); i++) {
			File myFile = new File(sendFilesPath.get(i));
			try {
				params.put(myFile.getName(), myFile);
			} catch (FileNotFoundException e1) {
				continue;
			}
		}

		client.setTimeout(10000);
		client.post(strUploadFile, params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable arg3) {
				Log.i("Show", "上傳失敗");
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				Log.i("Show", "上傳成功");
			}

			@Override
			public void onProgress(int bytesWritten, int totalSize) {
				super.onProgress(bytesWritten, totalSize);
				int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
				// 上傳進度顯示
				Log.i("Show", "上傳進度顯示:" + count);
				
			}

			@Override
			public void onRetry(int retryNo) {
				super.onRetry(retryNo);
				// 傳回重試次數
			}
		});
	}

}
           

記得加網絡權限

<uses-permission android:name="android.permission.INTERNET"/>
           

源碼下載下傳:

CSDN:http://download.csdn.net/detail/dickyqie/9702051