android與server端servlet交互
一個關于android與server端servlet交互的demo,比項目中的例子要簡單很多。
入門的朋友可以參考下。
核心代碼:
/**
*
* 項目名稱 JSONDemo
* 包 名 servlet
* 文 件 名 CustomerServlet.java
* 開 發 人 Administrator
* 描述信息 客戶端驗證用戶登陸Servlet
* 發布日期 2012-4-6下午03:28:47
* 修改日期
* 修 改 人
* 版本信息 V1.0
*
*/
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 314719472293387358L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//登陸成功標志
String LOGIN_FLAG="";
//獲得客戶端提交用戶名密碼
String username = req.getParameter("username");
String password = req.getParameter("password");
//調用UserDAO中isLogin方法判斷數據中用戶名密碼是否正確
boolean flag=UserDAO.isLogin(username, password);
try {
DataOutputStream output=new DataOutputStream(resp.getOutputStream());
if (flag) {
LOGIN_FLAG="success";
output.writeUTF("服務器端數據:"+LOGIN_FLAG);
System.out.println(LOGIN_FLAG);
output.writeInt(1);
output.close();
}else{
//登錄失敗
LOGIN_FLAG="failure";
System.out.println(LOGIN_FLAG);
output.writeUTF("服務器端數據:"+LOGIN_FLAG);
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
ClientDemo 核心代碼:
public class MainActivity extends Activity {
//private static final int REQUEST_CODE = 2;
HttpPost httpRequest=new HttpPost(UriAPI.HTTPCustomer);
EditText et_name;
EditText et_pwd;
TextView show_login;
Button btn_login;
Button btn_cancle;
ProgressDialog progressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//初始化登陸界面
btn_login=(Button) findViewById(R.id.btn_login);
btn_cancle=(Button) findViewById(R.id.btn_cancle);
et_name=(EditText) findViewById(R.id.et_name);
et_pwd = (EditText) findViewById(R.id.et_pwd);
show_login=(TextView) findViewById(R.id.show_login);
progressDialog = new ProgressDialog(this);
btn_login.setOnClickListener(new OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(View v) {
//通過AsyncTask類提交數據 異步顯示
new AT().execute(et_name.getText().toString(),et_pwd.getText().toString());
}
});
}
public class UriAPI {
/** 定義一個Uri **/
public static final String HTTPCustomer ="http://10.0.1.9:8026/JSONDemo/servlet/CustomerServlet";
}
@SuppressWarnings("rawtypes")
class AT extends AsyncTask{
String result="";
@Override
protected void onPreExecute() {
//加載progressDialog
progressDialog.show();
}
@Override
protected Object doInBackground(Object... params_obj) {
CharSequence username="";
CharSequence password="";
username=et_name.getText();
password =et_pwd.getText();
if(!username.equals("")&&!password.equals("")){
//請求數據
HttpPost httpRequest = new HttpPost(UriAPI.HTTPCustomer);
//創建參數
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username.toString()));
params.add(new BasicNameValuePair("password", password.toString()));
//params.add(new BasicNameValuePair("flag","0"));
try {
//對提交數據進行編碼
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
//獲取響應服務器的數據
if (httpResponse.getStatusLine().getStatusCode()==200) {
//利用字節數組流和包裝的綁定數據
byte[] data =new byte[2048];
//先把從服務端來的數據轉化成字節數組
data =EntityUtils. toByteArray((HttpEntity)httpResponse.getEntity());
//再創建字節數組輸入流對象
ByteArrayInputStream bais = new ByteArrayInputStream(data);
//綁定字節流和數據包裝流
DataInputStream dis = new DataInputStream(bais);
//將字節數組中的數據還原成原來的各種數據類型,代碼如下:
result=new String(dis.readUTF());
Log.i("服務器返回信息:", result);
}
} catch(ClientProtocolException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
@Override
protected void onPostExecute(Object result) {
//獲得服務器返回信息成功后
show_login.setText(result.toString());
//取消進度條
progressDialog.cancel();
}
}
}
界面截圖
1.未登錄

2.登陸中

3.登陸成功
4.登陸失敗

本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!