android-async-http 基本使用方法

来源:互联网 发布:mysql安装 编辑:程序博客网 时间:2024/05/16 08:08

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

本地测试成功



0 0
原创粉丝点击