zoukankan      html  css  js  c++  java
  • Android基础_web通信2

    一.移动客服端实现对PC端数据的操作

    在PC端模拟一个数据库,实现用户的增删改查,然后在移动客服端实现对PC端数据库的操作

    在PC端建立三个表

    用户表(Users),员工表(Emp), 部门表(Dept),

    User表对应字段,并设置对应的set/get方法,这里不一一写出

        private int uno;
        private String uname;
        private String upwd;

    Emp表对应字段

        private int eno;
        private String ename;
        private int eage;
        private String esex;
        private Date eintime;

    Dept表对应字段

        private int dno;
        private String dname;

    对数据库的模拟操作:

    pc端代码:

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    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 com.entity.Users;
    import com.google.gson.Gson;
    
    /**
     * 处理Users相关请求的控制类
     */
    @WebServlet("/UserServlet")
    public class UserServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        
        //定义一个集合,初始化一些用户
        private List<Users> userList;
        
        public UserServlet() {
            super();
            userList=new ArrayList<Users>();
            userList.add(new Users(1, "admins", "admins"));
            userList.add(new Users(2, "jack", "000000"));
            userList.add(new Users(3, "lucy", "000000"));
            userList.add(new Users(4, "toms", "000000"));
            userList.add(new Users(5, "join", "000000"));
        }
        
        //所有来到UserServlet的请求都将进入service中进行分发
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            //获取用户要请求的方法
            String method=request.getParameter("method");
            switch(method){
                case "login":
                    doLogin(request, response);
                    break;
                case "register":
                    doRegister(request, response);
                    break;
                case "userList":
                    doFindUserList(request, response);
                    break;
                case "userById":
                    doFindUserById(request, response);
                    break;
                case "updateUser":
                    doUpdateUser(request, response);
                    break;
                case "deleteUser":
                    doDeleteUser(request, response);
                    break;
            }
        }
    
        //用户登录
        protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //接收用户传递的参数
            String name=request.getParameter("uname");
            String pwd=request.getParameter("upwd");
            
            PrintWriter out=response.getWriter();
            for (Users users : userList) {
                if(users.getUname().equals(name)&&users.getUpwd().equals(pwd)){
                    out.println("用户登录成功");
                    return;
                }
            }
            out.print("用户名和密码错误");
            out.close();
        }
    
        //添加用户
        protected void doRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("----------进入添加用户操作----------");
            //接收用户传递的参数
            String name=request.getParameter("uname");
            String pwd=request.getParameter("upwd");
            
            //将信息封装成一个Users对象
            userList.add(new Users(userList.size()+1, name, pwd));
            PrintWriter out=response.getWriter();
            out.println("用户"+name+"添加成功");
            out.close();        
        }
        
        //查询所有用户
        protected void doFindUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out=response.getWriter();
            //将所有用户以JSON格式响应到客户端
            out.println(new Gson().toJson(userList));
            out.close();        
        }
        
        //根据Id查询单个用户
        protected void doFindUserById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out=response.getWriter();
            //取出ID
            int id=Integer.parseInt(request.getParameter("uno"));
            for (Users users : userList) {
                if(users.getUno()==id){
                    out.println(new Gson().toJson(users));
                    return;
                }
            }
            out.close();
        }
        
        //修改用户
        protected void doUpdateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            int id=Integer.parseInt(request.getParameter("uno"));
            String name=request.getParameter("uname");
            String pwd=request.getParameter("upwd");
            
            PrintWriter out=response.getWriter();
            for (Users users : userList) {
                if(users.getUno()==id){
                    users.setUname(name);
                    users.setUpwd(pwd);
                    out.println(new Gson().toJson("修改用户成功"));
                    return;
                }
            }
            out.println(new Gson().toJson("修改用户失败"));
            out.close();
        }
        
        //删除用户
        protected void doDeleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            int id=Integer.parseInt(request.getParameter("uno"));
            PrintWriter out=response.getWriter();
            for (Users users : userList) {
                if(users.getUno()==id){
                    userList.remove(users);
                    out.println(new Gson().toJson("删除用户成功"));
                    return;
                }
            }
            out.println(new Gson().toJson("删除用户失败"));
            out.close();
        }
    
    }

    HTML页面 :

    用户登录代码:<a href="http://localhost:8080/Web_Project/UserServlet?method=login&uname=xiaolin&upwd=000000">用户登录</a><br/><br/>,传参其他的相同

    PC端对数据的操作完成。

    手机客服端代码:

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Toast;
    
    import com.example.utils.CallBack;
    import com.example.utils.FileUtils;
    import com.example.utils.HttpUtils;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        //用户登录(自带模拟器:10.0.2.2,Genymotion:本地IP)
        public void doLogin(View view){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
    //192.168.3.183需要改成你的本地IP地址,下面的都需要改成你本地的IP地址 URL url
    =new URL("http://192.168.3.183:8080/Web_Project/UserServlet?method=login&uname=xiaolin&upwd=000000"); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.connect(); //获取结果 InputStream input=conn.getInputStream(); final String result= FileUtils.formatStreamToString(input); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //添加用户 public void doRegister(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet"); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//以POST方式传值 conn.setDoOutput(true);//允许向服务器传递参数,默认false conn.connect(); //向服务器传递数据java.net.URLEncoder.encode("","utf-8"); String data="method=register&uname=xiaolin&upwd=123456"; OutputStream out=conn.getOutputStream(); out.write(data.getBytes()); out.close(); //获取结果 InputStream input=conn.getInputStream(); final String result= FileUtils.formatStreamToString(input); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //查询所有用户 public void doFindUserList(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet?method=userList"); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.connect(); //直接将返回的流转换为一个字符串 String result=FileUtils.formatStreamToString(conn.getInputStream()); //如何解析一个JSON字符串 final JSONArray array=new JSONArray(result); runOnUiThread(new Runnable() { @Override public void run() { for(int i=0;i<array.length();i++){ try { JSONObject obj=array.getJSONObject(i); String msg="用户名:"+obj.getString("uname")+",密码:"+obj.getString("upwd"); Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //查询单个用户 public void doFindUserById(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet?method=userById&uno=1"); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.connect(); //直接将返回的流转换为一个字符串 String result=FileUtils.formatStreamToString(conn.getInputStream()); //如何解析一个JSON字符串 final JSONObject obj=new JSONObject(result); runOnUiThread(new Runnable() { @Override public void run() { String msg= null; try { msg = "用户名:"+obj.getString("uname")+",密码:"+obj.getString("upwd"); Toast.makeText(getApplicationContext(),msg, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //更新用户 public void doUpdateUser(View view){ new Thread(new Runnable() { @Override public void run() { try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet"); HttpURLConnection conn=(HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//以POST方式传值 conn.setDoOutput(true);//允许向服务器传递参数,默认false conn.connect(); //向服务器传递数据java.net.URLEncoder.encode("","utf-8"); String data="method=updateUser&uno=6&uname=xiaolin&upwd=111111"; OutputStream out=conn.getOutputStream(); out.write(data.getBytes()); out.close(); //获取结果 InputStream input=conn.getInputStream(); final String result= FileUtils.formatStreamToString(input); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(),result.toString(), Toast.LENGTH_SHORT).show(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //删除用户 public void doDeleteUser(View view){ try { URL url=new URL("http://192.168.3.183:8080/Web_Project/UserServlet"); String data="method=deleteUser&uno=6"; HttpUtils.doPost(url, data, new CallBack() { @Override public void success(final String str) { runOnUI(str); } @Override public void failed(final String str) { runOnUI(str); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } public void addEmp(View view){ try { URL url=new URL("http://192.168.3.183:8080/Web_Project/EmpServlet"); String data="method=addEmp&ename=小明&eage=21&esex=男&eintime=2017-7-8&dno=1"; HttpUtils.doPost(url, data, new CallBack() { @Override public void success(final String str) { runOnUI(str); } @Override public void failed(final String str) { runOnUI(str); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } public void findEmpList(View view){ try { URL url=new URL("http://192.168.3.183:8080/Web_Project/EmpServlet?method=empList"); HttpUtils.doGet(url,null, new CallBack() { @Override public void success(final String str) { try { final JSONArray array=new JSONArray(str); for(int i=0;i<array.length();i++){ JSONObject obj=array.getJSONObject(i); JSONObject dept=obj.getJSONObject("dept"); String empInfo="员工姓名"+obj.getString("ename")+",部门:"+dept.getString("dname"); runOnUI(empInfo); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void failed(final String str) { runOnUI("查询失败"); } }); } catch (MalformedURLException e) { e.printStackTrace(); } } private void runOnUI(final String str){ runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(),str, Toast.LENGTH_SHORT).show(); } }); } }
    工具类:
    FileUtils
    public class FileUtils {
    
        //将一个输入流转换为一个字符串
        public static String formatStreamToString(InputStream stream){
            if(stream!=null){
                ByteArrayOutputStream out=new ByteArrayOutputStream();
                byte[] bytes=new byte[1024];
                int len=0;
                try {
                    while((len=stream.read(bytes))!=-1){
                        out.write(bytes,0,len);
                    }
                    String str=out.toString();
                    out.flush();
                    out.close();
                    stream.close();
                    return str;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        //执行下载文件到指定位置
        public static void downLoadFile(final String fromPath, final String savePath, final CallBack callBack){
            if(fromPath!=null&&savePath!=null){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url=new URL(fromPath);
                            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                            conn.setConnectTimeout(20*1000);
                            conn.connect();
                            InputStream input=conn.getInputStream();
                            File file=new File(savePath);
                            if(!file.getParentFile().exists())
                                file.getParentFile().mkdirs();
                            OutputStream out=new FileOutputStream(file);
                            byte[] bytes=new byte[1024];
                            for(int len=0;(len=input.read(bytes))!=-1;){
                                out.write(bytes,0,len);
                            }
                            out.flush();
                            out.close();
                            input.close();
                            callBack.success(null);//下载成功
                        } catch (Exception e) {
                            e.printStackTrace();
                            callBack.failed(null);//下载失败
                        }
                    }
                }).start();
            }
        }
    
        public static boolean existsFile(String path){
            if(path!=null&&path.length()>0) {
                File file = new File(path);
                if(file.exists())
                    return true;
            }
            return false;
        }
    }
    
    
    HttpUtils
    public class HttpUtils {
    
        public static void doPost(final URL url, final String data, final CallBack callBack){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setConnectTimeout(10*1000);
                        conn.setDoOutput(true);
                        conn.setUseCaches(false);
                        conn.setInstanceFollowRedirects(true);
                        conn.connect();
                        if(data!=null&&data.length()>0){
                            OutputStream out=conn.getOutputStream();
                            out.write(data.getBytes());
                            out.close();
                        }
                        callBack.success(FileUtils.formatStreamToString(conn.getInputStream()));
                    } catch (IOException e) {
                        e.printStackTrace();
                        callBack.failed("操作出错");
                    }
    
                }
            }).start();
        }
    
        public static void doGet(final URL url,final String data,final CallBack callBack){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(10*1000);
                        conn.setDoOutput(true);
                        conn.setInstanceFollowRedirects(true);
                        conn.connect();
                        if(data!=null&&data.length()>0){
                            OutputStream out=conn.getOutputStream();
                            out.write(data.getBytes());
                            out.close();
                        }
                        callBack.success(FileUtils.formatStreamToString(conn.getInputStream()));
                    } catch (IOException e) {
                        e.printStackTrace();
                        callBack.failed("操作出错");
                    }
    
                }
            }).start();
        }
    }
    CallBack
    public interface CallBack {
    
        public void success(String str);
        public void failed(String str);
    }
    界面:

    手机客服端代码完成。

    
    
     
  • 相关阅读:
    MySQL必知必会(数据分组,Group by和Having子句, Select子句的顺序)
    MySQL必知必会(汇总数据, 聚集函数)
    MySQL必知必会(使用函数处理数据)
    菜根谭#206
    菜根谭#205
    菜根谭#204
    菜根谭#203
    菜根谭#202
    菜根谭#201
    菜根谭#200
  • 原文地址:https://www.cnblogs.com/Crezy/p/8118159.html
Copyright © 2011-2022 走看看