为什么80%的码农都做不了架构师?>>>
android-async-http是一个强大的第三方开源网络请求库,
官网源码:https://github.com/loopj/android-async-http
官网教程:http://loopj.com/android-async-http/
这个网络请求库是基于Apache HttpClient库之上的一个异步网络请求处理库,网络处理均基于Android的非UI线程,通过回调方法处理请求结果。
主要类介绍
AsyncHttpRequest
继承自Runnabler,被submit至线程池执行网络请求并发送start,success等消息
AsyncHttpResponseHandler
接收请求结果,一般重写onSuccess及onFailure接收请求成功或失败的消息,还有onStart,onFinish等消息
TextHttpResponseHandler
继承自AsyncHttpResponseHandler,只是重写了AsyncHttpResponseHandler的onSuccess和onFailure方法,将请求结果由byte数组转换为String
JsonHttpResponseHandler
继承自TextHttpResponseHandler,同样是重写onSuccess和onFailure方法,将请求结果由String转换为JSONObject或JSONArray
BaseJsonHttpResponseHandler
继承自TextHttpResponseHandler,是一个泛型类,提供了parseResponse方法,子类需要提供实现,将请求结果解析成需要的类型,子类可以灵活地使用解析方法,可以直接原始解析,使用gson等。
RequestParams
请求参数,可以添加普通的字符串参数,并可添加File,InputStream上传文件
AsyncHttpClient
核心类,使用HttpClient执行网络请求,提供了get,put,post,delete,head等请求方法,使用起来很简单,只需以url及RequestParams调用相应的方法即可,还可以选择性地传入Context,用于取消Content相关的请求,同时必须提供ResponseHandlerInterface(AsyncHttpResponseHandler继承自ResponseHandlerInterface)的实现类,一般为AsyncHttpResponseHandler的子类,AsyncHttpClient内部有一个线程池,当使用AsyncHttpClient执行网络请求时,最终都会调用sendRequest方法,在这个方法内部将请求参数封装成AsyncHttpRequest(继承自Runnable)交由内部的线程池执行。
SyncHttpClient
继承自AsyncHttpClient,同步执行网络请求,AsyncHttpClient把请求封装成AsyncHttpRequest后提交至线程池,SyncHttpClient把请求封装成AsyncHttpRequest后直接调用它的run方法。
服务器端php测试代码:
'success',
'get'=>json_encode($_GET),
'post'=>json_encode($_POST),
'upload'=>json_encode($_FILES)
);
echo json_encode($data);
?>
android客户端测试代码:
package com.penngo.http;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class HttpUtil {
private static final String BASE_URL = "http://192.168.17.99/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void setTimeout(){
client.setTimeout(60000);
}
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);
}
public static void download(String url, RequestParams params, FileAsyncHttpResponseHandler fileAsyncHttpResponseHandler){
client.get(getAbsoluteUrl(url), params, fileAsyncHttpResponseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
package com.penngo.http;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import org.apache.http.Header;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
public class MainActivity extends Activity {
private final static String tag = "MainActivity-->";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getBtn = (Button)this.findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
testGet();
}
});
Button postBtn = (Button)this.findViewById(R.id.postBtn);
postBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
testPost();
}
});
Button upLoadBtn = (Button)this.findViewById(R.id.upLoadBtn);
upLoadBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
testUploadFile();
}
});
Button downloadBtn = (Button)this.findViewById(R.id.downloadBtn);
downloadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
testDownloadFile();
}
});
}
private void testGet(){
HttpUtil.get("test/android.php", getParames(), responseHandler);
}
private RequestParams getParames(){
RequestParams params = new RequestParams();
params.put("user", "penngo");
params.put("psw", "penngo");
return params;
}
private TextHttpResponseHandler responseHandler = new TextHttpResponseHandler(){
@Override
public void onStart() {
Log.e(tag, "onStart====");
}
@Override
public void onSuccess(int statusCode, Header[] headers, String response) {
Log.e(tag, "onSuccess====");
StringBuilder builder = new StringBuilder();
for (Header h : headers) {
String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());
builder.append(_h);
builder.append("\n");
}
Log.e(tag, "statusCode:" + statusCode + " headers:" + builder.toString() + " response:" + response);
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable e) {
Log.e(tag, "onFailure====");
StringBuilder builder = new StringBuilder();
for (Header h : headers) {
String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());
builder.append(_h);
builder.append("\n");
}
Log.e(tag, "statusCode:" + statusCode + " headers:" + builder.toString(), e);
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
};
private void testPost(){
HttpUtil.post("test/android.php", getParames(), responseHandler);
}
private void testUploadFile(){
RequestParams params = new RequestParams();
try {
InputStream is = this.getAssets().open("png/launcher.png");
String png = this.getExternalCacheDir().getAbsolutePath() + "/launcher.png";
File myFile = new File(png);
Log.e(tag, "png====" + png);
this.copyToSD(png, "png/launcher.png");
params.put("pngFile", myFile, RequestParams.APPLICATION_OCTET_STREAM);
} catch(Exception e) {
Log.e(tag,"上传失败", e);
}
HttpUtil.post("test/android.php", params, responseHandler);
}
private void testDownloadFile(){
String mp3 = this.getExternalCacheDir().getAbsolutePath() + "/fa.mp3";
File mp3File = new File(mp3);
FileAsyncHttpResponseHandler fileHandler = new FileAsyncHttpResponseHandler(mp3File){
public void onSuccess(int statusCode, Header[] headers, File file){
Log.e(tag, "onSuccess====");
StringBuilder builder = new StringBuilder();
for (Header h : headers) {
String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());
builder.append(_h);
builder.append("\n");
}
Log.e(tag, "statusCode:" + statusCode + " headers:" + builder.toString() + " file:" + file.getAbsolutePath());
}
public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file){
}
};
HttpUtil.download("test/fa.mp3", null, fileHandler);
}
/**
* 复制文件到sdcard
*/
private void copyToSD(String strOut, String srcInput) throws IOException
{
InputStream myInput;
OutputStream myOutput = new FileOutputStream(strOut);
myInput = this.getAssets().open(srcInput);
byte[] buffer = new byte[1024];
int length = myInput.read(buffer);
while(length > 0)
{
myOutput.write(buffer, 0, length);
length = myInput.read(buffer);
}
myOutput.flush();
myInput.close();
myOutput.close();
}
}
执行输出结果:
E/MainActivity-->﹕ onStart====
E/MainActivity-->﹕ onSuccess====
E/MainActivity-->﹕ statusCode:200 headers:Date : Wed, 05 Aug 2015 04:30:00 GMT
Server : Apache/2.2.25 (Win32) mod_ssl/2.2.25 OpenSSL/0.9.8y mod_wsgi/3.3 Python/2.7.3
X-Powered-By : ZendServer 6.3.0
Set-Cookie : ZDEDebuggerPresent=php,phtml,php3; path=/
Keep-Alive : timeout=5, max=100
Connection : Keep-Alive
Transfer-Encoding : chunked
Content-Type : text/html
response:{"status":"success","get":"{\"user\":\"penngo\",\"psw\":\"penngo\"}","post":"[]","upload":"[]"}
E/MainActivity-->﹕ onStart====
E/MainActivity-->﹕ onSuccess====
E/MainActivity-->﹕ statusCode:200 headers:Date : Wed, 05 Aug 2015 04:30:15 GMT
Server : Apache/2.2.25 (Win32) mod_ssl/2.2.25 OpenSSL/0.9.8y mod_wsgi/3.3 Python/2.7.3
X-Powered-By : ZendServer 6.3.0
Set-Cookie : ZDEDebuggerPresent=php,phtml,php3; path=/
Keep-Alive : timeout=5, max=100
Connection : Keep-Alive
Transfer-Encoding : chunked
Content-Type : text/html
response:{"status":"success","get":"[]","post":"{\"user\":\"penngo\",\"psw\":\"penngo\"}","upload":"[]"}
E/MainActivity-->﹕ png====/mnt/sdcard/Android/data/com.penngo.http/cache/launcher.png
E/MainActivity-->﹕ onStart====
E/MainActivity-->﹕ onSuccess====
E/MainActivity-->﹕ statusCode:200 headers:Date : Wed, 05 Aug 2015 04:30:24 GMT
Server : Apache/2.2.25 (Win32) mod_ssl/2.2.25 OpenSSL/0.9.8y mod_wsgi/3.3 Python/2.7.3
X-Powered-By : ZendServer 6.3.0
Set-Cookie : ZDEDebuggerPresent=php,phtml,php3; path=/
Keep-Alive : timeout=5, max=100
Connection : Keep-Alive
Transfer-Encoding : chunked
Content-Type : text/html
response:{"status":"success","get":"[]","post":"[]","upload":"{\"pngFile\":{\"name\":\"launcher.png\",\"type\":\"application\\\/octet-stream\",\"tmp_name\":\"C:\\\\Windows\\\\Temp\\\\phpFDC4.tmp\",\"error\":0,\"size\":3418}}"}
E/MainActivity-->﹕ onSuccess====
E/MainActivity-->﹕ statusCode:200 headers:Date : Wed, 05 Aug 2015 04:30:30 GMT
Server : Apache/2.2.25 (Win32) mod_ssl/2.2.25 OpenSSL/0.9.8y mod_wsgi/3.3 Python/2.7.3
Last-Modified : Fri, 19 Dec 2014 08:10:00 GMT
ETag : "13200000000a25c-4776aa-50a8d3c355700"
Accept-Ranges : bytes
Content-Length : 4683434
Keep-Alive : timeout=5, max=100
Connection : Keep-Alive
Content-Type : audio/mpeg
file:/mnt/sdcard/Android/data/com.penngo.http/cache/fa.mp3