同步/异步:
同步: 在同一个线程里面执行的.
异步:开启新的线程
异步:开启新的线程
1.GET获取服务器信息:
public
class
MainActivity
extends
Activity {
private
TextView
tv_code
;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main
);
tv_code
=(TextView) findViewById(R.id.
tv_code
);
}
/**
* Button触发事件
*/
public
void
click(View view){
//创建AsyncHttpClient对象
AsyncHttpClient client=
new
AsyncHttpClient();
client.get(
"http://www.baidu.com"
,
new
AsyncHttpResponseHandler(){
@Override
public
void
onSuccess(String content) {
super
.onSuccess(content);
tv_code
.setText(content);
}
@Override
public
void
onFailure(Throwable error, String content) {
super
.onFailure(error, content);
Toast. makeText(getApplicationContext(),
"获取失败....."
, 0).show() ;
error.printStackTrace();
}
});
}
}
-------------------------------------------------------------------------------------------------
2.Get/Post请求提交数据到服务器
public
class
LoginService {
/**
* GET方法获取服务器信息
*
@param
context
*
@param
userName
*
@param
passWord
*/
public
static
void
loginByGet(
final
Context context,String userName,String passWord){
String path=
"http://192.168.1.8/Web/LoginServlet?userName="
+URLEncoder. encode(userName)+
"&passWord="
+URLEncoder.
encode
(passWord)
;
//创建AsyncHttpClient对象
AsyncHttpClient client=
new
AsyncHttpClient();
client.get(path,
new
AsyncHttpResponseHandler(){
@Override
public
void
onSuccess(String content) {
super
.onSuccess(content);
Toast. makeText(context,
"请求成功"
, 0).show();
}
@Override
public
void
onFailure(Throwable error, String content) {
super
.onFailure(error, content);
Toast. makeText(context,
"请求失败"
, 0).show();
error.printStackTrace();
//打印失败信息
}
});
}
/**
* POST方法提交数据到服务器
*
@param
context
*
@param
userName
*
@param
passWord
*/
public
static
void
(
final
Context context,String userName,String passWord){
String path=
"http://192.168.1.8/Web/LoginServlet"
;
//创建AsyncHttpClient对象
AsyncHttpClient client=
new
AsyncHttpClient();
RequestParams params=
new
RequestParams();
//创建信息提交者
params.put(
"userName"
, userName);
params.put(
"passWord"
, passWord);
client.post(path,
params,
new
AsyncHttpResponseHandler(){
@Override
public
void
onSuccess(String content) {
super
.onSuccess(content);
Toast. makeText(context,
"提交成功..."
, 0).show();
}
@Override
public
void
onFailure(Throwable error, String content) {
super
.onFailure(error, content);
Toast. makeText(context,
"提交失败"
, 0).show();
error.printStackTr ace();
//打印错误信息
}
});
}
}