android-async-http 开源的网络请求lib

2017-06-08  本文已影响0人  yanghanbin_it
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void getSubmit(View v) {
        EditText etName = (EditText) findViewById(R.id.et_name);
        EditText etPwd = (EditText) findViewById(R.id.et_password);
        String name = etName.getText().toString();
        String password = etPwd.getText().toString();
        String url = "http://192.168.1.105:8080/android/AndroidServlet?username="
                + URLEncoder.encode(name)
                + "&password="
                + URLEncoder.encode(password);
        // 创建异步请求
        AsyncHttpClient ahc = new AsyncHttpClient();
        // 发送get请求提交数据
        ahc.get(url, new MyResponseHandler());
    }
    public void postSubmit(View v) {
        EditText etName = (EditText) findViewById(R.id.et_name);
        EditText etPwd = (EditText) findViewById(R.id.et_password);
        String name = etName.getText().toString();
        String password = etPwd.getText().toString();
        String url = "http://192.168.1.105:8080/android/AndroidServlet";
        // 创建异步请求
        RequestParams rp = new RequestParams();
        rp.add("username", name);
        rp.add("password", password);
        AsyncHttpClient ahc = new AsyncHttpClient();
        ahc.post(url, rp, new MyResponseHandler());
    }
    class MyResponseHandler extends AsyncHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                byte[] responseBody) {
            try {
                Toast.makeText(MainActivity.this,
                        new String(responseBody, "utf-8"), 0).show();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onFailure(int statusCode, Header[] headers,
                byte[] responseBody, Throwable error) {
            Toast.makeText(MainActivity.this, "请求失败", 0).show();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读