Android 异步Http框架简介和实现原理
在前几篇文章中《Android 采用get方式提交数据到服务器》《Android 采用post方式提交数据到服务器》《Android 采用HttpClient提交数据到服务器》介绍了android的两种提交数据到服务器的方法
本文将介绍另外一种基于框架android-async-http的方法来实现
android-async-http是一个强大的网络请求库,这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。android-async-http是一个强大的第三方开源网络请求库
官网源码:https://github.com/loopj/android-async-http
官网教程:http://loopj.com/android-async-http/
新建项目,先到github上:https://github.com/loopj/android-async-http/tree/1.4.0
下载相应的zip文件,解压缩后将src中的com文件夹复制到项目的src目录
下面使用框架android-async-http,代码如下:
package com.wuyudong.asynchttp; import java.net.URLEncoder; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view) { // 用户名密码提交到服务器 AsyncHttpClient client = new AsyncHttpClient(); String path = "http://169.254.168.71:8080/web/LoginServlet?username=" + URLEncoder.encode("wuyudong") + "&password=" + URLEncoder.encode("123"); client.get(path, new AsyncHttpResponseHandler() { @Override public void onSuccess(String content) { // TODO Auto-generated method stub super.onSuccess(content); Toast.makeText(MainActivity.this, "请求成功!", 0).show(); } @Override public void onFailure(Throwable error, String content) { // TODO Auto-generated method stub super.onFailure(error, content); Toast.makeText(MainActivity.this, "请求失败!", 0).show(); } }); } }
可以看到代码量减少了很多
下面来实现一个精简版的异步框架
新建项目
AsyncHttpClient.java
package com.wuyudong.AsyncClient; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Message; public class AsyncHttpClient { public void get(final String path, final MyHandler myHandler) { new Thread() { @Override public void run() { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(path); try { HttpResponse response = client.execute(httpGet); InputStream is = response.getEntity().getContent(); String content = StreamTools.readInputStream(is); // 执行成功 Message msg = new Message(); msg.what = 0; msg.obj = "请求成功"; myHandler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); // 执行失败 Message msg = new Message(); msg.what = 1; msg.obj = "请求失败"; myHandler.sendMessage(msg); } } }.start(); } }
MainActivity.java
package com.wuyudong.AsyncClient; import java.net.URLEncoder; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view) { // 1、开启子线程 执行一个http请求,在后台执行 在子线程执行 // 2、 子线程执行完毕后通知ui界面 AsyncHttpClient client = new AsyncHttpClient(); String path = "http://169.254.168.71:8080/web/LoginServlet?username=" + URLEncoder.encode("wuyudong") + "&password=" + URLEncoder.encode("123"); client.get(path, new MyHandler() { @Override public void onFailure(String content) { Toast.makeText(MainActivity.this, content, 1).show(); super.onFailure(content); } @Override public void onSuccess(String content) { Toast.makeText(MainActivity.this, content, 0).show(); super.onSuccess(content); } }); } }
MyHandler.java
package com.wuyudong.AsyncClient; import android.os.Handler; import android.os.Message; public class MyHandler extends Handler { public void onFailure(String content) { } public void onSuccess(String content) { } @Override public void handleMessage(Message msg) { String content = (String) msg.obj; switch (msg.what) { case 0: onSuccess(content); break; case 1: onFailure(content); break; default: break; } super.handleMessage(msg); } }
StreamTools.java
package com.wuyudong.AsyncClient; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTools { /** * 把输入流的内容转化成字符串 * * @param is * @return */ public static String readInputStream(InputStream is) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } is.close(); baos.close(); byte[] result = baos.toByteArray(); String str = new String(result); // 试着解析result里面的字符串 if (str.contains("gb2312")) { return new String(result, "gb2312"); } else if(str.contains("utf-8")){ return str; } else { return null; } //return new String(result, "gb2312"); } catch (Exception e) { e.printStackTrace(); return null; } } }
作者:wuyudong
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
如果觉得本文对您有帮助,可以对作者进行小额【赞助】