android 訪問web應用

用手機訪問web應用的demo,總體思路是:html

 一、經過手機訪問web應用,並向服務器發送信息。java

二、服務器接收客戶端信息。node

三、服務器處理數據(解析xml文件)。android

四、重組信息,返回給客戶端。web

 1、服務器代碼服務器

首先,創建一個web工程:Test1app

而後新建一個servlet,用於手機客戶端調用。dom

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. <br> 
     */  
    public void destroy() {  
        super.destroy();   
    }    
    /** 
     * The doGet method of the servlet. <br> 
     * 
     * 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. <br> 
     * 
     * 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. <br> 
     * 
     * @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

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.4"   
    xmlns="http://java.sun.com/xml/ns/j2ee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  <servlet>  
    <description>This is the description of my J2EE component</description>  
    <display-name>This is the display name of my J2EE component</display-name>  
    <servlet-name>ServletDemo</servlet-name>  
    <servlet-class>ServletDemo</servlet-class>  
  </servlet>  
  
  <servlet-mapping>  
    <servlet-name>ServletDemo</servlet-name>  
    <url-pattern>/servlet/ServletDemo</url-pattern>  
  </servlet-mapping>  
  <welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
</web-app>

xml文件格式

<?xml version="1.0" encoding="GB2312" standalone="no"?>  
<employees>  
    <employee>  
        <name>user0</name>  
        <sex>m</sex>  
        <age>30</age>  
    </employee>  
</employees>

解析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;  
    }  
}

二,客戶端代碼jsp

一、新建Android工程ide

二、修改main。xml文件 

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText   
    android:layout_height="wrap_content"  
    android:id="@+id/address"  
    android:layout_width="fill_parent"  
    android:text="http://192.168.1.111:8089/Test1/servlet/ServletDemo"  
>  
</EditText>  
<Button  
     android:id="@+id/ButtonGo"   
     android:layout_width="wrap_content"   
     android:layout_height="wrap_content"  
     android:text="go!"  
 >  
</Button>  
<TextView    
    android:layout_width="fill_parent"   
    android:layout_height="fill_parent"   
    android:background="#ffffff"  
    android:textColor="#000000"  
    android:id="@+id/pagetext"  
    />  
</LinearLayout>

三、添加關鍵代碼

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());  
                }  
            }  
        });          
    }  
}

一、程序啓動二、發送請求後

小結。

一、整個demo比較簡單,但咱們又接觸到了新知識,這裏面須要注意的是,服務器的ip地址要用實際地址 上篇已經說明了緣由。

二、整個步驟比較簡單,首先客戶端建立鏈接,而後發送消息,最後接收消息,服務器同理。 

相關文章
相關標籤/搜索