您的位置:首页 > 移动开发 > Android开发

Android客户端和服务器交互

2013-04-16 22:17 309 查看
Android客户端和服务器交互实现流程:

(客户端输入的用户名和密码提交到服务器端判断后给出相应的操作。)



客户端代码:

activity_login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".LoginActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#00f"
        android:textSize="30px"
        android:text="Usrname: " />
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#00f"
        android:textSize="30px"
        android:text="Password: " />
    <EditText
        android:id="@+id/psd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/login"
        android:layout_width="102dp"
        android:layout_height="wrap_content"
        android:text=" Login " />

    <TextView
        android:id="@+id/sign"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>




LoginActivity.java为按钮注册单击事件

login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {//单击按钮后发出请求,获取相应结果,并处理。
				final Handler myHandler =new Handler(){
					public void handleMessage(Message msg) {
						String reponse =(String)msg.obj;
						if(reponse.equals("true")){
							Intent intent=new Intent(LoginActivity.this,MainActivity.class);
							startActivity(intent);
						}
						else{
							sign.setText("Username or password incorrect!plz retry.");
							Toast.makeText(LoginActivity.this,"Username or password incorrect!plz retry.",Toast.LENGTH_LONG);
						}
						
					}
				};
				new Thread(new Runnable(){
					@Override
					public void run() {
						LoginToServer logToServer=new LoginToServer();
						String result=logToServer.doGet(name.getText().toString(), psd.getText().toString());
						Message msg=new Message();
						msg.obj=result;
						//System.out.println(result);
						myHandler.sendMessage(msg);
					}
					
				}).start();
			}
		});


辅助类LoginToServer.java(通过相应方法连接到服务器并返回状态码)

public class LoginToServer {
	private String url="http://10.0.2.2:8080/zl/LoginServlet";
	String result="";
	
	public String doGet(String name,String psd){
		String urlStr=url+"?name="+name+"&psd="+psd;
		HttpClient hc=new DefaultHttpClient();
		HttpGet hg=new HttpGet(urlStr);
		try {
			HttpResponse resp=hc.execute(hg);
			//System.out.println(resp.getStatusLine().getStatusCode());
			if(resp.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				HttpEntity he=resp.getEntity();
				InputStream is=he.getContent();
				BufferedReader br=new BufferedReader(new InputStreamReader(is));
				String readLine=null;
				while((readLine=br.readLine())!=null){
					result +=readLine;
				}
			}
			else{
				result="error";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
				
		return result;
	}

注意 在***M中localhost(127.0.0.1)代指的是模拟器本身即手机,要访问本机的Tomcat服务器需用android内置的IP:10.0.2.2

需要在manifest.xml中配置允许网络访问的权限



服务器端代码:

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name=request.getParameter("name");
		String psd =request.getParameter("psd");
	
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//out.println(name);
		//out.println(psd);
		//这里判断的是固定的用户名和密码,当然可以数据库中读取
		if(name.equals("vonzhou") && psd.equals("vonzhou")){
			out.print(true);
		}else{
			out.print(false);
		}
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: