1. 程式人生 > >Android實戰簡易教程-第六十六槍(server端搭建和server端Json數據交互)

Android實戰簡易教程-第六十六槍(server端搭建和server端Json數據交互)

視頻 pack tis sta listen let Coding read ide

學習Android有一段時間了。對server端有非常深的好奇,決定對server端的實現進行一些研究,這裏實現了一個簡單的小樣例,用於獲取server端的json數據,樣例非常easy,適合剛開始學習的人學習使用。

server端

首先我們搭建server端,server端使用struct2架構,對該架構不熟悉的人能夠花一點時間看看慕課網上的相關視頻,這裏用myeclipse實現server端。

新建一個webproject。這裏要引入struct2相關,方法是:點擊新建的webproject郵件-》myeclipse選項-》project facets->選擇安裝struct2相關就可以。

技術分享圖片

看一下相關代碼:

struts.xml:

<?xml version="1.0" encoding="GBK"?>  
<!DOCTYPE struts PUBLIC  
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
        "http://struts.apache.org/dtds/struts-2.0.dtd">  

    <struts>  
        <package name="struts2" extends="struts-default" namespace="/">  
    <action name="getjson" class="com.shao.action.JSONAction" method="json">  
     <result  name="success">index.jsp</result>  
    </action>  
        </package>  
    </struts>  


web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Test2</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>
</web-app>


以下是JSONAction.java:

package com.shao.action;  
  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.struts2.interceptor.ServletRequestAware;  
import org.apache.struts2.interceptor.ServletResponseAware;  
  
import com.google.gson.Gson;  
import com.opensymphony.xwork2.ActionSupport;  
import com.shao.domain.Music;  
  
public class JSONAction extends ActionSupport implements ServletRequestAware,  
        ServletResponseAware {  
  
    /** 
     *  
     */  
    private static final long serialVersionUID = -3604892179657815531L;  
    private  HttpServletRequest request;  
    private  HttpServletResponse  response;  
    private  String  format;  
    public String getFormat() {  
        return format;  
    }  
  
    public void setFormat(String format) {  
        this.format = format;  
    }  
  
    @Override  
    public void setServletRequest(HttpServletRequest request) {  
        this.request = request;  
    }  
  
    @Override  
    public void setServletResponse(HttpServletResponse response) {  
        this.response = response;  
    }  
      
    public  void json(){  
        List<Music> list = new ArrayList<Music>();  
        Gson gson = new  Gson();  
        Music m1 = new Music();  
        m1.setId(1);  
        m1.setAuthor("周傑倫");  
        m1.setName("外婆");  
        m1.setTime("04:04");  
        list.add(m1);  
        Music m2 = new Music();  
        m2.setId(2);  
        m2.setAuthor("周傑倫");  
        m2.setName("半獸人");  
        m2.setTime("04:05");  
        list.add(m2);  
        Music m3 = new Music();  
        m3.setId(3);  
        m3.setAuthor("周傑倫");  
        m3.setName("烏克麗麗");  
        m3.setTime("02:55");  
        list.add(m3);  
        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {  
        }.getType();  //指定type
        String beanListToJson = gson.toJson(list,type);  //list轉換成json字符串
        System.out.println("GSON-->"+beanListToJson);     
        try {    
             response.setCharacterEncoding("UTF-8");   
            this.response.getWriter().write(beanListToJson);    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
    }  
}  


最後是Music類:(這個類在Android程序中也須要)

package com.shao.domain;  
  
public class Music {  
  
        private Integer id;    
        private String name;    
        private String time;  
        private String  author;  
        public Integer getId() {  
            return id;  
        }  
        public void setId(Integer id) {  
            this.id = id;  
        }  
        public String getName() {  
            return name;  
        }  
        public void setName(String name) {  
            this.name = name;  
        }  
        public String getTime() {  
            return time;  
        }  
        public void setTime(String time) {  
            this.time = time;  
        }  
        public String getAuthor() {  
            return author;  
        }  
        public void setAuthor(String author) {  
            this.author = author;  
        }   
} 


好了,以下選擇project右鍵:run as->myeclipse server application:

?

技術分享圖片

註意,本項目的端口選擇的是8888,yayun表示本機。

這時在瀏覽器地址欄輸入:http://yayun:8888/Test2/getjson.action

出現例如以下 :

技術分享圖片

說明server端搭建成功。

另外,本系統json解析用到了Gson的jar包,要自己導入哦,下載Gson引入到項目中,Android端也須要這個jar包。

移動端

移動端用eclipse實現

技術分享圖片

首先是JsonClientActivity:

package com.test.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.testandroid.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class JsonClientActivity extends Activity {
	private Button update;
	private ListView listView;
	private String jsonResult;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			jsonResult=(String) msg.obj;
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		update = (Button) findViewById(R.id.update);
		listView = (ListView) findViewById(R.id.list);
		update.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String urlStr = "http://192.168.0.103:8888/Test2/getjson.action";
				
				getJson(urlStr);
				String jString=jsonResult;
				List<Music> list = GsonUtil.getListFromJson(jString);
				System.out.println(list);
				if (list != null) {
					System.out.println(list);
					List<Map<String, Object>> data = getAdapterData(list);

					SimpleAdapter adapter = new SimpleAdapter(JsonClientActivity.this, data, R.layout.list,
							new String[] { "name", "author", "time" }, new int[] { R.id.name, R.id.author, R.id.time });
					listView.setAdapter(adapter);
				}

				
			}
		});
	}

	private List<Map<String, Object>> getAdapterData(List list) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			Music music = (Music) list.get(i);
			map.put("name", music.getName());
			map.put("author", music.getAuthor());
			map.put("time", music.getTime());
			data.add(map);
		}
		return data;
	}
	/**
	 * 異步獲取json字符串
	 * @param url
	 */
	
    public   void getJson(final String  url){  
 	   
 	   new Thread(new Runnable() {
			
			@Override
			public void run() {
				  URL urlString;
				try {
					urlString = new URL(url);
					HttpURLConnection httpURLConnection=(HttpURLConnection) urlString.openConnection();
					httpURLConnection.setConnectTimeout(5000);
					httpURLConnection.setDoInput(true);
					httpURLConnection.setRequestMethod("GET");
					httpURLConnection.connect();
					
					InputStream inputStream=httpURLConnection.getInputStream();
					InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
					
					BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
					StringBuilder stringBuilder=new StringBuilder();
					String line;
					while ((line=bufferedReader.readLine())!=null) {
						stringBuilder.append(line);
					}
					System.out.println(new String());
					Message message=new Message();
					message.obj=new String(stringBuilder.toString());
					handler.sendMessage(message);
					
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		    	   
				
			}
		}).start();
          
    } 
}


然後是工具類:

package com.test.demo;  
  
import java.util.List;

import com.google.gson.Gson;  
  
public class GsonUtil {  
 
   public  static  List<Music>  getListFromJson(String json){  
        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {  
        }.getType();  
        Gson gson = new Gson();  
        List<Music>  list  = gson.fromJson(json, type);  
        return list;  
   }  
} 


布局類非常easy就不寫了。能夠自行下載源代碼。執行Android程序:

技術分享圖片

執行不成功的註意網絡權限。

源代碼下載:

server端

Android端

?

歡迎關註我和我的微信平臺,謝謝


?

?

Android實戰簡易教程-第六十六槍(server端搭建和server端Json數據交互)