使用开源框架android-async-http-1.4.8.jar与服务器传输数据

先在libs文件夹下放入android-async-http-1.4.8.jar
源码

public class MainActivity extends Activity {

    private TextView username;
    private TextView password;
    private Button button;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//获取用户上传的用户名和密码     
        username = (TextView) findViewById(R.id.username);
        password = (TextView) findViewById(R.id.password);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                String us = username.getText().toString();
                String pd = password.getText().toString();
//需要将android-async-http-**.jar放在libs包里
                AsyncHttpClient client = new AsyncHttpClient();  
 //指定url路径  
                String url = "http://acm.hpu.edu.cn/PowerWeb/system/ElectricAction_getElecMonth.do?format=json";  
//封装文件上传的参数  
                RequestParams params = new RequestParams();  
                 params.put("username", un);
                 params.put("password", pd);
//设置连接超时
                 client.setConnectTimeout(5000);
//使用post方式上传参数
                 client.post(url,params, new AsyncHttpResponseHandler() {
//连接开始                      
                        public void onStart() {
                            System.out.println("连接开始");                 
                        }

//连接失败
                        public void onFailure(int arg0, Header[] arg1,
                                byte[] arg2, Throwable arg3) {
System.out.println("连接失败");                         
                        }
//连接成功
                        public void onSuccess(int arg0, Header[] arg1,
                                byte[] arg2) {
//接收服务器返还的参数arg2
                            String str = new String(arg2);
System.out.println("str:"+str);

                        }

//连接结束
                        public void onFinish() {
System.out.println("连接结束");
                        }
                });

    }
    });}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


}

    }


你可能感兴趣的:(android)