朋友让写一个关于android与server端servlet交互的demo,比项目中的例子要简单很多。
入门的朋友可以参考下。
核心代码:
01
/**
02
*
03
* 项目名称 JSONDemo
04
* 包名 servlet
05
* 文件名 CustomerServlet.java
06
* 开发人 Administrator
07
* 描述信息 客户端验证用户登陆Servlet
08
* 发布日期 2012-4-6下午03:28:47
09
* 修改日期
10
* 修改人
11
* 版本信息 V1.0
12
*
13
*/
14
public class CustomerServlet extends HttpServlet {
15
16
private static final long serialVersionUID = 314719472293387358L;
17
18
@Override
19
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
20
throws ServletException, IOException {
21
//登陆成功标志
22
String LOGIN_FLAG="";
23
//获得客户端提交用户名密码
24
String username = req.getParameter("username");
25
String password = req.getParameter("password");
26
//调用UserDAO中isLogin方法判断数据中用户名密码是否正确
27
boolean flag=UserDAO.isLogin(username, password);
28
try {
29
DataOutputStream output=new DataOutputStream(resp.getOutputStream());
30
if (flag) {
31
LOGIN_FLAG="success";
32
output.writeUTF("服务器端数据:"+LOGIN_FLAG);
33
System.out.println(LOGIN_FLAG);
34
output.writeInt(1);
35
output.close();
36
}else{
37
//登录失败
38
LOGIN_FLAG="failure";
39
System.out.println(LOGIN_FLAG);
40
output.writeUTF("服务器端数据:"+LOGIN_FLAG);
41
output.close();
42
}
43
} catch (Exception e) {
44
e.printStackTrace();
45
}
46
47
}
48
}
ClientDemo 核心代码:
001
public class MainActivity extends Activity {
002
//private static final int REQUEST_CODE = 2;
003
HttpPost httpRequest=new HttpPost(UriAPI.HTTPCustomer);
004
EditText et_name;
005
EditText et_pwd;
006
TextView show_login;
007
Button btn_login;
008
Button btn_cancle;
009
ProgressDialog progressDialog;
010
/** Called when the activity is first created. */
011
@Override
012
public void onCreate(Bundle savedInstanceState) {
013
super.onCreate(savedInstanceState);
014
setContentView(R.layout.main);
015
//初始化登陆界面
016
btn_login=(Button) findViewById(R.id.btn_login);
017
btn_cancle=(Button) findViewById(R.id.btn_cancle);
018
et_name=(EditText) findViewById(R.id.et_name);
019
et_pwd = (EditText) findViewById(R.id.et_pwd);
020
show_login=(TextView) findViewById(R.id.show_login);
021
022
progressDialog = new ProgressDialog(this);
023
btn_login.setOnClickListener(new OnClickListener() {
024
025
@SuppressWarnings("unchecked")
026
@Override
027
public void onClick(View v) {
028
//通过AsyncTask类提交数据 异步显示
029
new AT().execute(et_name.getText().toString(),et_pwd.getText().toString());
030
}
031
});
032
033
}
034
public class UriAPI {
035
/** 定义一个Uri **/
036
public static final String HTTPCustomer ="http://10.0.1.9:8026/JSONDemo/servlet/CustomerServlet";
037
}
038
@SuppressWarnings("rawtypes")
039
class AT extends AsyncTask{
040
041
String result="";
042
@Override
043
protected void onPreExecute() {
044
//加载progressDialog
045
progressDialog.show();
046
}
047
048
@Override
049
protected Object doInBackground(Object... params_obj) {
050
CharSequence username="";
051
CharSequence password="";
052
053
username=et_name.getText();
054
055
password =et_pwd.getText();
056
if(!username.equals("")&&!password.equals("")){
057
//请求数据
058
HttpPost httpRequest= new HttpPost(UriAPI.HTTPCustomer);
059
//创建参数
060
List<NameValuePair> params=new ArrayList<NameValuePair>();
061
params.add(new BasicNameValuePair("username", username.toString()));
062
params.add(new BasicNameValuePair("password", password.toString()));
063
//params.add(new BasicNameValuePair("flag","0"));
064
try {
065
//对提交数据进行编码
066
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
067
HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
068
//获取响应服务器的数据
069
if (httpResponse.getStatusLine().getStatusCode()==200) {
070
//利用字节数组流和包装的绑定数据
071
byte[] data =new byte[2048];
072
//先把从服务端来的数据转化成字节数组
073
data =EntityUtils. toByteArray((HttpEntity)httpResponse.getEntity());
074
//再创建字节数组输入流对象
075
ByteArrayInputStream bais = new ByteArrayInputStream(data);
076
//绑定字节流和数据包装流
077
DataInputStream dis = new DataInputStream(bais);
078
//将字节数组中的数据还原成原来的各种数据类型,代码如下:
079
result=new String(dis.readUTF());
080
Log.i("服务器返回信息:", result);
081
}
082
} catch(ClientProtocolException e){
083
e.printStackTrace();
084
}catch(UnsupportedEncodingException e){
085
e.printStackTrace();
086
} catch (IOException e) {
087
e.printStackTrace();
088
}
089
090
}
091
return result;
092
}
093
094
@Override
095
protected void onPostExecute(Object result) {
096
097
//获得服务器返回信息成功后
098
show_login.setText(result.toString());
099
//取消进度条
100
progressDialog.cancel();
101
}
102
103
}
104
}
界面截图
1.未登录
2.登陆中
3.登陆成功
4.登陆失败