您的位置:首页 > 理论基础 > 计算机网络

android-async-http 基本使用方法

2016-12-05 11:02 501 查看
我用的是android studio,在Gradle中添加依赖 
compile 'cz.msebera.android:httpclient:4.3.6'
compile 'com.loopj.android:android-async-http:1.4.9'
更新依赖,下载架包在项目中放2个按钮,分别用于,get、post请求在MainActivity中的代码,引入架包
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.*;
AsyncHttpClient client = new AsyncHttpClient();
public void btn_get(View v) {
final String path = "http://192.168.20.146:8080/test/LoginServlet?username="+ URLEncoder.encode("zhuyu")+"&password="+URLEncoder.encode("123456");
client.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
String content = new String(response);
Toast.makeText(MainActivity.this,"get:" + content,0).show();
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
String content = new String(errorResponse);
Toast.makeText(MainActivity.this,"get:,出现异常",0).show();
}
});
}

public void btn_post(View v) {
final String path = "http://192.168.20.146:8080/test/LoginServlet";
RequestParams params = new RequestParams();
params.put("username", "zhuyu");
params.put("password", "123456");
client.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String content = new String(responseBody);
Toast.makeText(MainActivity.this,"post:" + content,0).show();
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
String content = new String(responseBody);
Toast.makeText(MainActivity.this,"post:,出现异常",0).show();
}
});
}
本地测试成功
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android