安卓应用服务器端开发。如果没有服务端,那么安卓应用就少了一条腿。
最近在做一个自动化办公的app,因此需要将手机端的数据存储到服务器端。所以在此详细记录下学习过程,供大家参考。
因为安卓的开发者大部分熟悉JAVA语言,我也不例外。所以我选择了TOMCAT+Severlet来搭建我的服务端。
在myeclipse 新建一个severlet ,并发布到tomcat服务器。安卓应用端通过http协议进行数据交互。
下面是实现登陆验证的详细过程。
服务器端:
package mySeverlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Severlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //request.setCharacterEncoding("UTF-8"); String name = request.getParameter("username"); //out.print(name); String pass = request.getParameter("password"); //out.print(pass); if(name.equals("luozhanwei")&&pass.equals("123456")) { out.print("success"); } else { out.println("failed"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //通常将dopost和doget合二为一 doGet(request, response); } }
import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.ConnectivityManager; import android.net.NetworkInfo.State; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.Settings; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Toast; public class LoginDemoActivity extends Activity { /** Called when the activity is first created. */ private Button loginBtn; private Button registerBtn; private EditText inputUsername; private EditText inputPassword; private ProgressDialog mDialog; private String responseMsg = ""; private static final int REQUEST_TIMEOUT = 5*1000;//设置请求超时10秒钟 private static final int SO_TIMEOUT = 10*1000; //设置等待数据超时时间10秒钟 private static final int LOGIN_OK = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); loginBtn = (Button)findViewById(R.id.login_btn_login); registerBtn = (Button)findViewById(R.id.login_btn_zhuce); inputUsername = (EditText)findViewById(R.id.login_edit_account); inputPassword = (EditText)findViewById(R.id.login_edit_pwd); //登录 loginBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { mDialog = new ProgressDialog(LoginDemoActivity.this); mDialog.setTitle("登陆"); mDialog.setMessage("正在登陆服务器,请稍后..."); mDialog.show(); Thread loginThread = new Thread(new LoginThread()); loginThread.start(); } }); registerBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(); intent.setClass(LoginDemoActivity.this, RegisterActivity.class); startActivity(intent); } }); } private boolean loginServer(String username, String password) { boolean loginValidate = false; //使用apache HTTP客户端实现 String urlStr = "http://10.0.2.2:8080/Login/Login"; HttpPost request = new HttpPost(urlStr); //如果传递参数多的话,可以对传递的参数进行封装 List<NameValuePair> params = new ArrayList<NameValuePair>(); //添加用户名和密码 params.add(new BasicNameValuePair("username",username)); params.add(new BasicNameValuePair("password",password)); try { //设置请求参数项 request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpClient client = getHttpClient(); //执行请求返回相应 HttpResponse response = client.execute(request); //判断是否请求成功 if(response.getStatusLine().getStatusCode()==200) { loginValidate = true; //获得响应信息 responseMsg = EntityUtils.toString(response.getEntity()); } }catch(Exception e) { e.printStackTrace(); } return loginValidate; } //初始化HttpClient,并设置超时 public HttpClient getHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); HttpClient client = new DefaultHttpClient(httpParams); return client; } //Handler Handler handler = new Handler() { public void handleMessage(Message msg) { switch(msg.what) { case 0: mDialog.cancel(); Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(LoginDemoActivity.this, MainActivity.class); startActivity(intent); finish(); break; case 1: mDialog.cancel(); Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_SHORT).show(); break; case 2: mDialog.cancel(); Toast.makeText(getApplicationContext(), "URL验证失败", Toast.LENGTH_SHORT).show(); break; } } }; //LoginThread线程类 class LoginThread implements Runnable { @Override public void run() { String username = inputUsername.getText().toString(); String password = inputPassword.getText().toString(); System.out.println("username="+username+":password="+password); //URL合法,但是这一步并不验证密码是否正确 boolean loginValidate = loginServer(username, password); System.out.println("----------------------------bool is :"+loginValidate+"----------response:"+responseMsg); Message msg = handler.obtainMessage(); if(loginValidate) { if(responseMsg.equals("success")) { msg.what = 0; handler.sendMessage(msg); }else { msg.what = 1; handler.sendMessage(msg); } }else { msg.what = 2; handler.sendMessage(msg); } } } }