发送post请求
-
使用RequestParams对象封装要携带的数据
//创建异步httpclient对象 AsyncHttpClient ahc = new AsyncHttpClient(); //创建RequestParams封装要携带的数据 RequestParams rp = new RequestParams(); rp.add("name", name); rp.add("pass", pass); //发送post请求 ahc.post(path, rp, new MyHandler());
案例代码
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void post(View v){
EditText et_name = (EditText) findViewById(R.id.et_name);
EditText et_pass = (EditText) findViewById(R.id.et_pass);
final String name = et_name.getText().toString();
final String pass = et_pass.getText().toString();
String url = "http://192.168.13.13/Web/servlet/CheckLogin";
//创建异步httpclient
AsyncHttpClient ahc = new AsyncHttpClient();
//发送post请求提交数据
//把要提交的数据封装至RequestParams对象
RequestParams params = new RequestParams();
params.add("name", name);
params.add("pass", pass);
ahc.post(url, params, new MyResponseHandler());
}
//响应处理器
class MyResponseHandler extends AsyncHttpResponseHandler{
//请求服务器成功时,此方法调用
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
}
//请求失败此方法调用
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "请求失败", 0).show();
}
}
}