jiashuai 2013-11-26
在iOS开发中有大名鼎鼎的ASIHttpRequest库,用来处理网络请求操作,今天要介绍的是一个在Android上同样强大的网络请求库android-async-http,目前非常火的应用Instagram和Pinterest的Android版就是用的这个网络请求库。这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。
其主要特征如下:
AsyncHttpClient client = new AsyncHttpClient(); client.get(http://www.baidu.com, new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { //返回的josn字符串 System.out.println(response); Log.v(TAG , "response"+response); } @Override public void onStart() { //开始 super.onStart(); Log.v(TAG , "onStart"); } @Override public void onFailure(Throwable error, String content) //出错 { Log.e(TAG , "onFailure error : " + error.toString() + "content : " + content); } @Override public void onFinish() { //结束 super.onFinish(); Log.v(TAG , "onFinish"); } });通过Get请求指定的URL并通过回调函数处理请求结果,同时,请求方式还支持POST和PUT,请求的同时还支持参数传递,下面看看如何通过JSON字符串作为参数访问服务器:
try { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "ryantang"); StringEntity stringEntity = new StringEntity(jsonObject.toString()); client.post(MainActivity.this, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){ @Override public void onSuccess(JSONObject jsonObject) { super.onSuccess(jsonObject); } }); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
public void downloadClick(View view) { String url = "http://f.hiphotos.baidu.com/album/w%3D2048/sign=38c43ff7902397ddd6799f046dbab3b7/9c16fdfaaf51f3dee973bf7495eef01f3b2979d8.jpg"; HttpUtil.get(url, new BinaryHttpResponseHandler() { @Override public void onSuccess(byte[] arg0) { super.onSuccess(arg0); File file = Environment.getExternalStorageDirectory(); File file2 = new File(file, "cat"); file2.mkdir(); file2 = new File(file2, "cat.jpg"); try { FileOutputStream oStream = new FileOutputStream(file2); oStream.write(arg0); oStream.flush(); oStream.close(); textView.setText("已经保存在sdcard里面"); } catch (Exception e) { e.printStackTrace(); Log.i("hck", e.toString()); } } }); }
public void uploadClick(View view){ String path="http://10.0.2.2:8080/jsontest/servlet/UploadServlet"; File myFile = new File("/sdcard/cat/cat.jpg"); RequestParams params = new RequestParams(); try { params.put("filename", myFile); AsyncHttpClient client = new AsyncHttpClient(); client.post(path, params, new AsyncHttpResponseHandler(){ @Override public void onSuccess(int statusCode, String content) { // TODO Auto-generated method stub super.onSuccess(statusCode, content); Toast.makeText(MainActivity.this, "上传成功!", Toast.LENGTH_LONG).show(); } }); } catch(FileNotFoundException e) { } }
<uses-permission android:name="android.permission.INTERNET" />gitbub上还提供了一套异步库: Android-Query(AQuery)是一个轻量级的开发包,用于实现Android上的异步任务和操作UI元素.(目前好像已经停止更新维护了)