博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android 访问web应用
阅读量:5943 次
发布时间:2019-06-19

本文共 10102 字,大约阅读时间需要 33 分钟。

hot3.png

用手机访问web应用的demo,整体思路是:

 1、通过手机访问web应用,并向服务器发送信息。

2、服务器接收客户端信息。

3、服务器处理数据(解析xml文件)。

4、重组信息,返回给客户端。

 一、服务器代码

首先,建立一个web工程:Test1

然后新建一个servlet,用于手机客户端调用。

import java.io.BufferedReader;  import java.io.BufferedWriter;  import java.io.FileNotFoundException;  import java.io.IOException;  import java.io.InputStreamReader;  import java.io.OutputStreamWriter;  import java.io.PrintWriter;  import java.util.ArrayList;  import java.util.List;  import javax.servlet.ServletException;  import javax.servlet.ServletInputStream;  import javax.servlet.ServletOutputStream;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import javax.xml.parsers.DocumentBuilder;  import javax.xml.parsers.DocumentBuilderFactory;  import javax.xml.parsers.ParserConfigurationException;    import org.w3c.dom.Document;  import org.w3c.dom.Node;  import org.w3c.dom.NodeList;  import org.xml.sax.SAXException;      public class ServletDemo extends HttpServlet {        /**      * Constructor of the object.      */      public ServletDemo() {          super();      }        /**      * Destruction of the servlet. 
*/ public void destroy() { super.destroy(); } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); this.doPost(request, response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //获得客户端发送的数据 ServletInputStream is = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String requestString = reader.readLine(); //向客户端返回数据 String responseString = processStringRequest(requestString,request); ServletOutputStream os = response.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write(responseString); //关闭资源 writer.flush(); writer.close(); reader.close(); os.close(); } /** * Initialization of the servlet.
* * @throws ServletException if an error occure */ public void init() throws ServletException { } private String processStringRequest(String requestString,HttpServletRequest request){ List list = this.toRead(request.getRealPath("/")+"user.xml"); String response = ""; if(null != list && list.size() > 0){ for(int i = 0 ; i < list.size(); i++){ JavaBean a = (JavaBean)list.get(i); response += "client say:"+requestString+"server say: this is your info:"+a.getName()+"@"+a.getSex()+"@"+a.getAge(); System.out.println(a.getName()); } }else{ response = "is wrong!"; } return response; } public List toRead(String filename) { List alist = new ArrayList(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(filename); NodeList employees = document.getChildNodes(); for (int i = 0; i < employees.getLength(); i++) { Node employee = employees.item(i); NodeList employeeInfo = employee.getChildNodes(); for (int j = 0; j < employeeInfo.getLength(); j++) { Node node = employeeInfo.item(j); NodeList employeeMeta = node.getChildNodes(); JavaBean bean = new JavaBean(); boolean status = false; for (int k = 0; k < employeeMeta.getLength(); k++) { if(employeeMeta.item(k).getNodeName().equals("name")){ bean.setName(employeeMeta.item(k).getTextContent()); } if(employeeMeta.item(k).getNodeName().equals("age")){ bean.setAge(employeeMeta.item(k).getTextContent()); } if(employeeMeta.item(k).getNodeName().equals("sex")){ bean.setSex(employeeMeta.item(k).getTextContent()); } status = true; } if(status){ alist.add(bean); } } } } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } return alist; } }

web工程的web.xml

This is the description of my J2EE component
This is the display name of my J2EE component
ServletDemo
ServletDemo
ServletDemo
/servlet/ServletDemo
index.jsp

xml文件格式

user0
m
30

解析xml文件用到的javabean:

public class JavaBean {            private String name;      private String sex;      private String age;      public String getAge() {          return age;      }      public void setAge(String age) {          this.age = age;      }      public String getName() {          return name;      }      public void setName(String name) {          this.name = name;      }      public String getSex() {          return sex;      }      public void setSex(String sex) {          this.sex = sex;      }  }

二,客户端代码

1、新建Android工程

2、修改main。xml文件 

3、添加关键代码

import android.app.Activity;  import android.os.Bundle;  import android.widget.Button;  import android.widget.TextView;  import android.util.Log;  import android.view.View;  import java.io.BufferedReader;  import java.io.BufferedWriter;  import java.io.InputStreamReader;  import java.io.OutputStreamWriter;  import java.net.URL;  import java.net.URLConnection;      public class ClientDemo extends Activity {      /** Called when the activity is first created. */        @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);                     final TextView tView = (TextView) findViewById(R.id.pagetext);                             final Button button = (Button) findViewById(R.id.ButtonGo);          button.setOnClickListener(new Button.OnClickListener() {              public void onClick(View v) {                                    String response_string = "";                  boolean out = true;                  boolean in = true;                  try {                      System.out.println("ty"+tView.getText().toString());                      URL url = new URL("http://192.168.1.111:8089/Test1/servlet/ServletDemo");                      URLConnection connection = url.openConnection();                                            connection.setDoInput(in);                      connection.setDoOutput(out);                                            BufferedWriter writer = null;                      //向服务器发送数据                      if(out){                          writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));                          writer.write("I am clent request!!");                          writer.flush();                      }                      //接受服务器返回的数据                      BufferedReader reader = null;                      if(in){                          reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));                          response_string = reader.readLine();                          System.out.println("response: "+response_string);                          Log.v("test", response_string);                          tView.setText(response_string);                      }                        if(writer != null){                          writer.close();                      }                                            if(reader != null){                          reader.close();                      }                  } catch (Exception e) {                      // TODO: handle exception                      System.out.println(e.getMessage());                  }              }          });              }  }

1、程序启动2、发送请求后

小结。

1、整个demo比较简单,但我们又接触到了新知识,这里面需要注意的是,服务器的ip地址要用实际地址 上篇已经说明了原因。

2、整个步骤比较简单,首先客户端创建连接,然后发送消息,最后接收消息,服务器同理。 

转载于:https://my.oschina.net/xiahuawuyu/blog/81789

你可能感兴趣的文章
从前后端分离到GraphQL,携程如何用Node实现?\n
查看>>
JavaScript标准库系列——RegExp对象(三)
查看>>
Linux Namespace系列(09):利用Namespace创建一个简单可用的容器
查看>>
关于缓存命中率的几个关键问题!
查看>>
oracle中create table with as和insert into with as语句
查看>>
kafka连接异常
查看>>
11g废弃的Hint - BYPASS_UJVC
查看>>
为什么工业控制系统需要安全防护?
查看>>
Mongodb部署记录[3]-主从搭建
查看>>
hive sql操作
查看>>
tomcat 深度优化
查看>>
127 - "Accordian" Patience
查看>>
Mac 常用快捷键
查看>>
阿里云CentOS7安装Oracle11GR2
查看>>
nginc+memcache
查看>>
php正则匹配utf-8编码的中文汉字
查看>>
MemCache在Windows环境下的搭建及启动
查看>>
linux下crontab实现定时服务详解
查看>>
返回顶部JS
查看>>
iOS9 HTTP 不能正常使用的解决办法
查看>>