一.移动客服端实现对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);
}
界面:

手机客服端代码完成。


 

Android基础_web通信2的更多相关文章

  1. Android基础_web通信3

    在Android基础_web通信2中,我运用的JSONObject是Android原生的json类,通过import org.json.JSONObject来导入. 还有另外一种更简单的方法,就是用G ...

  2. Android基础_web通信

    一.发展史 1G 模拟制式手机,只能进行语音通话2G 数字制式手机,增加接收数据等功能3G 智能手机,它已经成了集语音通信和多媒体通信相结合,并且包括图像.音乐.网页浏览.电话会议以及其它一些信息服务 ...

  3. Andorid基础_web通信_webView案例

    一.创建Activity,layout文件 activity_web_view.xml代码: <?xml version="1.0" encoding="utf-8 ...

  4. Android基础总结(8)——服务

    服务(Service)是Android中实现程序后台运行的解决方案,它非常适合用于去执行哪些不需要和用户交互而且还要长期运行的任务.服务的运行不依赖任何用户界面,即使当程序被切换到后台,或者用户打开了 ...

  5. 【Xamarin开发 Android 系列 4】 Android 基础知识

    原文:[Xamarin开发 Android 系列 4] Android 基础知识 什么是Android? Android一词的本义指“机器人”,同时也是Google于2007年11月5日宣布的基于Li ...

  6. 【朝花夕拾】Android性能篇之(七)Android跨进程通信篇

    前言 只要是面试高级工程师岗位,Android跨进程通信就是最受面试官青睐的知识点之一.Android系统的运行由大量相互独立的进程相互协助来完成的,所以Android进程间通信问题,是做好Andro ...

  7. android基础---->service的生命周期

    服务是一个应用程序组件代表应用程序执行一个长时间操作的行为,虽然不与用户交互或供应功能供其它应用程序使用.它和其他的应用对象一样,在他的宿主进程的主线程中运行.今天我们开始android中普通serv ...

  8. Android基础——Fragment控制切换多个页面

    今天接着上一篇文章,讲解一下Fragment的控制,主要是切换View和页面替换等操作.还有就是如何获取Fragment的管理对象,以及与Activity的通信方式. (PS:新建的QQ群,有兴趣可以 ...

  9. Android基础新手教程——4.1.3 Activity登堂入室

    Android基础新手教程--4.1.3 Activity登堂入室 标签(空格分隔): Android基础新手教程 本节引言: 好的,在学习了两节的Activity后相信大家已经知道怎样去使用Acti ...

随机推荐

  1. Java并发编程实践读书笔记(1)线程安全性和对象的共享

    2.线程的安全性 2.1什么是线程安全 在多个线程访问的时候,程序还能"正确",那就是线程安全的. 无状态(可以理解为没有字段的类)的对象一定是线程安全的. 2.2 原子性 典型的 ...

  2. myeclipse无法导入项目

    MyEclipse无法导入Java项目时常遇到的两种情况: 1.Some projects cannot be imported because they already exist in the w ...

  3. git入门(msysgit安装)

    1.下载git-for-windows 常用的GitHub客户端msysgit,也就是git-for-windows. 登录官网 https://git-for-windows.github.io/, ...

  4. 【java】彩票中奖码生成器:java.util.Random里的方法public int nextInt(int bound)

    package 彩票中奖码生成器; import java.util.Random; public class TestRandom { public static void main(String[ ...

  5. bzoj 4345: [POI2016]Korale

    Description 有n个带标号的珠子,第i个珠子的价值为a[i].现在你可以选择若干个珠子组成项链(也可以一个都不选),项链的价值为所有珠子的价值和.现在给所有可能的项链排序,先按权值从小到大排 ...

  6. SpringMVC底层数据传输校验的方案(修改版)

    团队的项目正常运行了很久,但近期偶尔会出现BUG.目前观察到的有两种场景:一是大批量提交业务请求,二是生成批量导出文件.出错后,再执行一次就又正常了. 经过跟踪日志,发现是在Server之间进行jso ...

  7. vue入坑总结

    1.Do not mount Vue to <html> or <body> - mount to normal elements instead. Vue2.x之后不推荐挂载 ...

  8. KVM(一):KVM安装

    KVM通俗的说就是一台服务器当多台用,详细介绍去百度和谷歌. 首先查看服务器是否支持虚拟化 [root@KVM ~]# grep -E '(vmx|svm)' /proc/cpuinfo --colo ...

  9. Linux目录结构介绍-http://yangrong.blog.51cto.com/6945369/1288072

    1.树状目录结构图 2./目录 目录 描述 / 第一层次结构的根.整个文件系统层次结构的根目录. /bin/ 需要在单用户模式可用的必要命令(可执行文件):面向所有用户,例如:cat.ls.cp,和/ ...

  10. c#的关键字

    abstract as base bool break byte case catch char checked decimal default delegate continue double do ...