android-async-http 基本使用方法

我用的是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();
            }
        });
    }

本地测试成功



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值