使用异步HttpClient框架发送get、post请求

https://github.com/ 搜索 asyn-http https://github.com/search?utf8=✓&q=asyn-http 下载 loopj/android-async-http

public class MainActivity extends Activity {

    Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void click1(View v){
//获取用户输入的账号密码
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass); String name = et_name.getText().toString();
String pass = et_pass.getText().toString(); String path = "http://169.254.244.136/Web2/servlet/Login";
//使用异步HttpClient发送get请求
AsyncHttpClient client = new AsyncHttpClient(); //把要提交的数据封装在rp对象中
RequestParams rp = new RequestParams();
rp.put("name", name);
rp.put("pass", pass);
//发送get请求
client.get(path, rp, new MyHandler());
} class MyHandler extends AsyncHttpResponseHandler{ //请求成功时回调,相应码为200
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
} //请求失败时回调,相应码不为200
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "请求失败", 0).show();
} } public void click2(View v){
//获取用户输入的账号密码
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass); String name = et_name.getText().toString();
String pass = et_pass.getText().toString(); String path = "http://169.254.244.136/Web2/servlet/Login"; //使用异步HttpClient发送post请求
AsyncHttpClient client = new AsyncHttpClient(); //把要提交的数据封装在rp对象中
RequestParams rp = new RequestParams();
rp.put("name", name);
rp.put("pass", pass);
//发送get请求
client.post(path, rp, new MyHandler());
} }
05-02 01:28