前提是要導入Asynchttpclient lib包
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// [1]找到我們關(guān)心的控件
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
// 點擊按鈕 進行g(shù)et方式提交數(shù)據(jù)
public void click1(View v) {
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
//[2.1]定義get方式要提交的路徑 小細節(jié) 如果提交中文要對name 和 pwd 進行一個urlencode 編碼
try {
path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//[3]使用開源項目進行g(shù)et請求
//[3.1]創(chuàng)建asynchttpclient
AsyncHttpClient client = new AsyncHttpClient();
//[3.2]進行g(shù)et 請求
client.get(path, new AsyncHttpResponseHandler() {
//請求成功的回調(diào)方法
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
Toast.makeText(getApplicationContext(), new String(responseBody,"gbk"), 1).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//請求失敗
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}
// [1]點擊按鈕 進行post方式提交數(shù)據(jù)
public void click2(View v) {
//[2]獲取用戶名和密碼
String name = et_username.getText().toString().trim();
String pwd = et_password.getText().toString().trim();
String path = "http://192.168.11.73:8080/login/LoginServlet";
//[3.1]創(chuàng)建asynchttpclient
AsyncHttpClient client = new AsyncHttpClient();
//[3.1.0]準備請求體的內(nèi)容
RequestParams params = new RequestParams();
params.put("username", name);
params.put("password", pwd);
//[3.2]進行post請求 params 請求的參數(shù)封裝
client.post(path, params, new AsyncHttpResponseHandler() {
//請求成功 登錄成功
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
Toast.makeText(getApplicationContext(), new String(responseBody,"gbk"), 1).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}
}