今天给大家分享一个github上Top1的Android异步网络请求框架的使用方法,我给大家分享一个它的基本用法。

先来一个简单的get请求

AsyncHttpClient client = new AsyncHttpClient();client.get("http://www.google.com", new AsyncHttpResponseHandler() {    @Override    public void onStart() {        // called before request is started    }    @Override    public void onSuccess(int statusCode, Header[] headers, byte[] response) {        // called when response HTTP status is "200 OK"    }    @Override    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {        // called when response HTTP status is "4XX" (eg. 401, 403, 404)    }    @Override    public void onRetry(int retryNo) {        // called when request is retried    }});

这样用我们每次都要new 非常的麻烦,我们可以简单的封装一下,直接调用静态方法,并且对域名做统一添加,自动转换为最终的url请求地址

import com.loopj.android.http.*;public class TwitterRestClient {  private static final String BASE_URL = "http://api.twitter.com/1/";  private static AsyncHttpClient client = new AsyncHttpClient();  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {      client.get(getAbsoluteUrl(url), params, responseHandler);  }  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {      client.post(getAbsoluteUrl(url), params, responseHandler);  }  private static String getAbsoluteUrl(String relativeUrl) {      return BASE_URL + relativeUrl;  }}

然后这样使用,请求返回一个Json类型的返回值

TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {       @Override       public void onSuccess(int statusCode, Header[] headers, JSONObject response) {           // If the response is JSONObject instead of expected JSONArray       }       @Override       public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {           // Pull out the first event on the public timeline           JSONObject firstEvent = timeline.get(0);           String tweetText = firstEvent.getString("text");           // Do something with the response           System.out.println(tweetText);       }   });

添加GET / POST参数 RequestParams

//建立空 RequestParams 并立即添加一些参数:RequestParams params = new RequestParams();params.put("key", "value");params.put("more", "data");//创建 RequestParams 一个参数:RequestParams params = new RequestParams("single", "value");//创建 RequestParams 从现有的 地图 键/值的字符串:HashMap<String, String> paramMap = new HashMap<String, String>();paramMap.put("key", "value");RequestParams params = new RequestParams(paramMap);

上传文件 RequestParams

//添加一个 InputStream 到 RequestParams 上传:InputStream myInputStream = blah;RequestParams params = new RequestParams();params.put("secret_passwords", myInputStream, "passwords.txt");//添加一个 文件 对象的 RequestParams 上传:File myFile = new File("/path/to/file.png");RequestParams params = new RequestParams();try {    params.put("profile_picture", myFile);} catch(FileNotFoundException e) {}//添加一个字节数组 RequestParams 上传:byte[] myByteArray = blah;RequestParams params = new RequestParams();params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

下载数据数据, FileAsyncHttpResponseHandler

#FileAsyncHttpResponseHandler 类可以被用来获取二进制数据 照片和其他文件。 例如:
AsyncHttpClient client = new AsyncHttpClient();client.get("http://example.com/file.png", new FileAsyncHttpResponseHandler(/* Context */ this) {    @Override    public void onSuccess(int statusCode, Header[] headers, File response) {        // Do something with the file `response`    }});

添加HTTP基本身份验证凭据

//一些请求可能需要用户名/密码凭据在处理API使用HTTP基本身份验证请求访问的服务。 您可以使用这个方法 setBasicAuth() 提供您的凭据。//设置用户名/密码对任何主机和领域特定的请求。 默认情况下,任何主机的认证范围,港口和领域。AsyncHttpClient client = new AsyncHttpClient();client.setBasicAuth("username","password/token");client.get("http://example.com");//您还可以提供更具体的认证范围(推荐)AsyncHttpClient client = new AsyncHttpClient();client.setBasicAuth("username","password", new AuthScope("example.com", 80, AuthScope.ANY_REALM));client.get("http://example.com");

持久化Cookie存储与 PersistentCookieStore

//这个库还包含一个 PersistentCookieStore 这是一个实现 Apache HttpClient CookieStore 接口,自动保存 饼干, SharedPreferences 存储在Android设备上。//这是非常有用的,如果你想使用cookie来管理身份验证 会话,因为用户将继续登录即使关闭 重启应用程序。//首先,创建的实例 AsyncHttpClient :AsyncHttpClient myClient = new AsyncHttpClient();//现在将这个客户的cookie存储的一个新实例 PersistentCookieStore ,由一个活动或应用程序上下文 (通常是 这 就足够了):PersistentCookieStore myCookieStore = new PersistentCookieStore(this);myClient.setCookieStore(myCookieStore);//任何Cookie收到服务器将会存储在持久化CookieStore。//添加自己的CookieStore ,只需构建一个新的Cookie和 调用 addCookie :BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");newCookie.setVersion(1);newCookie.setDomain("mydomain.com");newCookie.setPath("/");myCookieStore.addCookie(newCookie);

下载 | 点击这里

github地址 | 点击这里

/** * -------------- * 欢迎转载 | 转载请注明 * -------------- * @author zsl * @github https://github.com/yy1300326388 * @blog http://blog.csdn.net/yy1300326388 */

更多相关文章

  1. Android实现文件上传功能(接收端用strust2)
  2. WebView中调用系统相册或拍照上传
  3. 工程 android上传图片至服务器
  4. Android WebView 支持H5图片上传
  5. Android上传图片(PHP服务器)
  6. lua学习笔记 3 android调用Lua。Lua脚本使用LoadLib回调Java,并
  7. Android DNS之DNS参数设置

随机推荐

  1. android 滚动视图(ScrollView)学习与应用
  2. [odroid-pc]ubuntu12.04 android adb she
  3. android新开发语言Kotlin的入手Demo
  4. 另类Android onClickListener 使用
  5. 初学Android,使用原始资源(二十三)
  6. 我的Android进阶之旅------>android api
  7. 【Android导航决 千里之行 始于足下】问
  8. Android 2.3 Webkit
  9. 移植havlenapetr的ffmpeg-->Android播放
  10. Zxing二维码自定义修改关键代码