PHP代码
<?php
header("Content-type: text/html; charset=gb2312");?>
Android代码
public static final int ISLOGIN =1;
private void sendRequestWithHttpClient(){
new Thread(new Runnable() {
@Override
public void run() {
//创建键/值组列表
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("name", qq_name.getText().toString()));
pairs.add(new BasicNameValuePair("pass", qq_pass.getText().toString()));
pairs.add(new BasicNameValuePair("security", security.getText().toString()));
try{
HttpClient httpClient = new DefaultHttpClient(); //定义HttpClient
HttpPost httpPost = new HttpPost("http://.........../android/registered.php"); //实例化HTTP方法
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"gb2312");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost); //执行请求
//处理返回数据
HttpEntity httpentity =httpResponse.getEntity();
InputStream is =httpentity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is,"gb2312"));
StringBuilder sb =new StringBuilder();
sb.append(reader.readLine() +"\n");
String line ="0";
while((line =reader.readLine())!=null){
sb.append(line +"\n");
}
is.close();
result = sb.toString();
Message message = new Message();
message.what = ISLOGIN;
handler.sendMessage(message); // 将Message对象发送出去,采用异步处理机制
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
// String result = EntityUtils.toString(httpResponse.getEntity());
}else{
}
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//异步处理的代码
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(Message msge) {
switch (msge.what) {
case ISLOGIN:
// 在这里可以进行UI操作
Toast.makeText(LoginActivity.this, "account or password is invalid",
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
注意:重新开启一个线程处理HttpClient请求,不要在UI线程处理,注意编码方式,如果出现乱码,数据库插入操作失败,将返回null值。