使用開源框架android-async-http-1.4.8.jar與伺服器傳輸資料
阿新 • • 發佈:2019-02-18
先在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;
}
}
}