天天看點

asynchttpclient android studio,網絡請求架構----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

效果圖:

案例如下:

1 public class MainActivity extends Activity implements OnClickListener {

2

3     public static AsyncHttpClient mHttpc = new AsyncHttpClient();

4

5     private TextView mTextView;

6

7     @Override

8     protected void onCreate(Bundle savedInstanceState) {

9         super.onCreate(savedInstanceState);

10         setContentView(R.layout.activity_asynchttpclict);

11         initView();

12     }

13

14     private void initView() {

15         findViewById(R.id.btn1).setOnClickListener(this);

16         findViewById(R.id.btn2).setOnClickListener(this);

17         findViewById(R.id.btn3).setOnClickListener(this);

18         findViewById(R.id.btn4).setOnClickListener(this);

19         mTextView=(TextView) findViewById(R.id.Text);

20     }

21

22     @Override

23     public void onClick(View v) {

24         switch (v.getId()) {

25         case R.id.btn1:

26             showHttpGet1();

27             break;

28         case R.id.btn2:

29             showHttpGet2("https://www.baidu.com");

30             break;

31         case R.id.btn3:

32             showHttpGet3();

33             break;

34         case R.id.btn4:

35             showHttpPost();

36             break;

37         case R.id.btn5:

38

39         case R.id.btn6:

40

41         default:

42             break;

43         }

44

45     }

46

47     private void showHttpGet1() {

48         AsyncHttpClient client = new AsyncHttpClient();

49         client.get("https://www.baidu.com", new AsyncHttpResponseHandler() {

50             @Override

51             public void onStart() { // 請求啟動 請求前

52             }

53

54             @Override

55             public void onSuccess(int statusCode, Header[] headers,

56                     byte[] responseBody) { // 請求成功

57                 StringBuffer result = new StringBuffer("");

58                 int length = responseBody.length;

59                 for (int i = 0; i < length; i++) {

60                     result.append((char) (responseBody[i] & 0xff));

61                 }

62                 Toast.makeText(MainActivity.this, "結果:" + result.toString(), 2)

63                         .show();

64                 mTextView.setText("結果:" +result.toString());

65             }

66

67             @Override

68             public void onFailure(int statusCode, Header[] headers,

69                     byte[] responseBody, Throwable error) // 請求失敗

70             {

71

72             }

73

74             public void onRetry() { // 重試

75

76             }

77

78             @Override

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

80

81             }

82

83             @Override

84             public void onFinish() { // 請求完成

85

86             }

87         });

88     }

89

90     public void showHttpGet2(String uri) {

91         mHttpc.get(uri, null, new AsyncHttpResponseHandler() { // 請求失敗

92                     @Override

93                     public void onFailure(int arg0, Header[] arg1, byte[] arg2,

94                             Throwable arg3) {

95                     }

96

97                     @Override

98                     public void onSuccess(int arg0, Header[] arg1,

99                             byte[] responseBody) {

100                         StringBuffer result = new StringBuffer("");

101                         int length = responseBody.length;

102                         for (int i = 0; i < length; i++) {

103                             result.append((char) (responseBody[i] & 0xff));

104                         }

105                         Toast.makeText(MainActivity.this,

106                                 "結果:" + result.toString(), 2).show();

107                         mTextView.setText("結果:" +result.toString());

108                     }

109                 });

110     }

111

112     private void showHttpGet3() {

113         AsyncHttpClient client = new AsyncHttpClient();

114         RequestParams params = new RequestParams();

115         params.put("q", "test");

116         params.put("showapi_appid", "11548");

117         // 目前時間

118         params.put("showapi_timestamp", "20160511151954");

119         params.put("showapi_sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");

120         client.get("https://route.showapi.com/32-9", params,

121                 new TextHttpResponseHandler() {

122                     @Override

123                     public void onSuccess(int statusCode, Header[] headers,

124                             String response) {

125                         Toast.makeText(MainActivity.this,

126                                 "結果:" + response.toString(), 2).show();

127                         mTextView.setText("結果:" +response.toString());

128                     }

129

130                     @Override

131                     public void onFailure(int statusCode, Header[] headers,

132                             String responseBody, Throwable error) {

133                         Log.i("ERROR", error.toString());

134                     }

135                 });

136     }

137

138    

141     public void showHttpPost() {

142         AsyncHttpClient client = new AsyncHttpClient();

143         RequestParams params = new RequestParams();

144         params.put("q", "test");

145         params.put("showapi_appid", "11548");

146         // 目前時間

147         params.put("showapi_timestamp", "20160511151954");

148         params.put("showapi_sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");

149         client.post("https://route.showapi.com/32-9", params,

150                 new AsyncHttpResponseHandler() {

151

152                     @Override

153                     public void onFailure(int arg0, Header[] arg1,

154                             byte[] responseBody, Throwable arg3) {

155

156                     }

157

158                     @Override

159                     public void onSuccess(int arg0, Header[] arg1,

160                             byte[] responseBody) {

161                         StringBuffer result = new StringBuffer("");

162                         int length = responseBody.length;

163                         for (int i = 0; i < length; i++) {

164                             result.append((char) (responseBody[i] & 0xff));

165                         }

166                         Toast.makeText(MainActivity.this,

167                                 "結果:" + result.toString(), 2).show();

168                         mTextView.setText("結果:" +result.toString());

169                     }

170                 });

171

172     }

173

174

175

176    

179     private void showFile() {

180         File myFile = new File("filePath");// filePath--->檔案路徑

181         RequestParams params = new RequestParams();

182         try {

183             params.put("time", "20160511151954");

184             params.put("sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");

185             params.put("filename", myFile);

186             AsyncHttpClient client = new AsyncHttpClient();

187             client.post("url", params, new AsyncHttpResponseHandler() {

188

189                 @Override

190                 public void onFailure(int arg0, Header[] arg1, byte[] arg2,

191                         Throwable arg3) {

192

193                 }

194

195                 @Override

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

197

198                 }

199             });

200         } catch (FileNotFoundException e) {

201             e.printStackTrace();

202         }

203     }

204    

209     public void uploadFile(ArrayList sendFilesPath) {

210         if (sendFilesPath.size() == 0)

211             return;

212

213         String strUploadFile = "";

214         AsyncHttpClient client = new AsyncHttpClient();

215         client.setURLEncodingEnabled(false);

216

217         RequestParams params = new RequestParams();

218         params.put("time", "20160511151954");

219         params.put("sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");

220         // 批量上傳

221         for (int i = 0; i < sendFilesPath.size(); i++) {

222             File myFile = new File(sendFilesPath.get(i));

223             try {

224                 params.put(myFile.getName(), myFile);

225             } catch (FileNotFoundException e1) {

226                 continue;

227             }

228         }

229

230         client.setTimeout(10000);

231         client.post(strUploadFile, params, new AsyncHttpResponseHandler() {

232

233             @Override

234             public void onFailure(int statusCode, Header[] headers,

235                     byte[] responseBody, Throwable arg3) {

236                 Log.i("Show", "上傳失敗");

237             }

238

239             @Override

240             public void onSuccess(int statusCode, Header[] headers,

241                     byte[] responseBody) {

242                 Log.i("Show", "上傳成功");

243             }

244

245             @Override

246             public void onProgress(int bytesWritten, int totalSize) {

247                 super.onProgress(bytesWritten, totalSize);

248                 int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);

249                 // 上傳進度顯示

250                 Log.i("Show", "上傳進度顯示:" + count);

251

252             }

253

254             @Override

255             public void onRetry(int retryNo) {

256                 super.onRetry(retryNo);

257                 // 傳回重試次數

258             }

259         });

260     }

261

262 }

記得加網絡權限

源碼下載下傳:

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