程序代码:
Runnable runnable = new Runnable() {
@Override
public void run() {
// 该部分是传参并更新控件
Message msg = new Message();
msg.what = -1;
// 发送消息到Handler
CommonData app = (CommonData)getApplication();
HttpPost request = new HttpPost(app.getLoginaddress());// wcf地址
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// 构造json
JSONStringer vehicle;
try {
// Message为方法参数名字
vehicle = new JSONStringer().object().key("user").object().key("UserName")
.value(edittext_user_username.getText().toString().trim()).key("PassWord")
.value(edittext_user_pwd.getText().toString().trim()).endObject()
.endObject();
// 向WCF服务发送请求
StringEntity entity = new StringEntity(vehicle.toString(), "UTF-8");
request.setEntity(entity);//
DefaultHttpClient httpClient = new DefaultHttpClient();
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != 200) {
// 加载失败界面
msg.what = 1;
} else {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Integer integer = Integer.valueOf(line.replaceAll("\\D+", "")
.replaceAll("\r", "").replaceAll("\n", "").trim());
if (integer > 0) {
//保存登录用户ID
app.setUserid(integer.toString());
} else {
msg.what = 0;
Log.d("****passworderror****", "passworderror");
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
msg.what = 1;
} finally {
if (msg.what == -1) {
msg.what = 101;
}
handler.sendMessage(msg);
}
}
};