android----AsyncHttpClient的get,post和圖片上傳

async-http-client庫是一個基於回調函數的Http異步通訊客戶端Android組件,是在Apache的HttpClient庫的基礎上開發構建而成的。html

 

Eclipse使用:導入android-async-http-1.4.4.jar 包, 點擊下載java

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

 

功能特點

  • 利用版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

 

效果圖:git

    

 

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);
				// 返回重試次數
			}
		});
	}

}

記得加網絡權限github

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

 

源碼點擊下載:https://github.com/DickyQie/android-network-requestjson

相關文章
相關標籤/搜索