android 38 Abdroid客户端和服务端交互

服务端:

package com.sxt.day05;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.sxt.day05.entity.User;

@WebServlet("/Login")
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    ArrayList users;
    
    public Login() {
        super();
        User user=new User("张飞", "1234", "13377889966", "[email protected]");
        users=new ArrayList<>();
        users.add(user);
        user=new User("王菲", "1234", "13577889966", "[email protected]");
        users.add(user);
        user=new User("刘亦菲", "1234", "133077889966", "[email protected]");
        users.add(user);
        user=new User("咖啡", "1234", "13877889966", "[email protected]");
        users.add(user);
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");//获取客户端发过来的名字
        if(name==null){
            return ;
        }
        name=new String(name.getBytes("iso8859-1"),"utf-8");
        String pwd=request.getParameter("pwd");
        for(int i=0;i){
            User user=users.get(i);
            if(name.equals(user.getName())&&pwd.equals(user.getPwd())){
                ObjectMapper om=new ObjectMapper();//jackson-core-asl.jar
                om.writeValue(response.getOutputStream(), user);//将user对象以输出流发送给客户端
                System.out.println(user.toString());
                break;
            }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList list=new ArrayList<>();
        request.setCharacterEncoding("utf-8");
        String name=request.getParameter("name");
        for(int i=0;i){
            User user=users.get(i);
            if(user.getName().indexOf(name)>=0){//name在user的名字中
                list.add(user);
            }
        }
        ObjectMapper om=new ObjectMapper();
        om.writeValue(response.getOutputStream(), list);
    }

}

 客户端:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical">
    <EditText 
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入姓名"
        android:text="菲"/>
    <EditText 
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入登陆密码"
        android:text="123456"
        android:password="true"/>
    
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GET方式登陆" />
    <Button
        android:id="@+id/btnQuery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="POST方式查询" />
    
LinearLayout>

客户端Activity:

package com.sxt.day06_03;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.client.utils.URLEncodedUtils;
import org.codehaus.jackson.map.ObjectMapper;

import com.sxt.day06.entity.User;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String PATH="http://10.0.2.2:8080/Day06_Servlet/Login_Servlet";//服务端地址
    
    EditText metName,metPwd;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setListener();
    }

    private void setListener() {
        setLoginClickListener();
        setQueryClickListener();
    }

    private void setQueryClickListener() {//查询,POST方式
        findViewById(R.id.btnQuery).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){//访问网络要在工作线程搞
                    public void run() {
                        String name=metName.getText().toString();
                        name="name="+name;
                        try {
                            byte[] data=name.getBytes("utf-8");
                            URL url=new URL(PATH);
                            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                            conn.setConnectTimeout(5000);
                            conn.setReadTimeout(5000);
                            conn.setRequestMethod("POST");
                            conn.setDoOutput(true);//像服务端发送数据
                            OutputStream out = conn.getOutputStream();
                            out.write(data);
                            out.flush();
                            if(conn.getResponseCode()!=200){
                                return ;
                            }
                            ObjectMapper om=new ObjectMapper();
                            List users=om.readValue(conn.getInputStream(), List.class);
                            Log.i("main",users.toString());
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    };
                }.start();
            }
        });
    }

    private void setLoginClickListener() {
        findViewById(R.id.btnLogin).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){//访问网络要在工作线程搞
                    public void run() {
                        String name=metName.getText().toString();
                        String password=metPwd.getText().toString();
                        StringBuilder sb=new StringBuilder(PATH);//PATH地址
                        try {
                            sb.append("?name=").append(URLEncoder.encode(name, "utf-8"))
                            .append("&password=").append(password);
                            URL url=new URL(sb.toString());//
                            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                            conn.setReadTimeout(5000);//读取权限5秒,否则断开
                            conn.setConnectTimeout(5000);//连接时间5秒,否则断开
                            conn.setRequestMethod("GET");//
                            if(conn.getResponseCode()!=200){
                                Toast.makeText(MainActivity.this, "连接服务端失败", 2000).show();
                                return ;
                            }
                            ObjectMapper om=new ObjectMapper();
                            User user = om.readValue(conn.getInputStream(), User.class);
                            Log.i("main",user.toString());
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    };
                }.start();
            }
        });
    }

    private void initView() {
        metName=(EditText) findViewById(R.id.etName);
        metPwd=(EditText) findViewById(R.id.etPassword);
    }

}

客户端项目描述文件:

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sxt.day06_03"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"/>   安卓想访问网络要申请网络权限
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.sxt.day06_03.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>
        activity>
    application>

manifest>

 

你可能感兴趣的:(android 38 Abdroid客户端和服务端交互)