美文网首页
android-async-http 开源的网络请求lib

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

作者: yanghanbin_it | 来源:发表于2017-06-08 15:03 被阅读0次
    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();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:android-async-http 开源的网络请求lib

          本文链接:https://www.haomeiwen.com/subject/wzxtqxtx.html