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


學習Android有一段時間了,對服務器端有很深的好奇,決定對服務器端的實現進行一些研究,這里實現了一個簡單的小例子,用於獲取服務器端的json數據,例子很簡單,適合初學者學習使用。

服務器端

首先我們搭建服務器端,服務器端使用struct2架構,對該架構不熟悉的人可以花一點時間看看慕課網上的相關視頻,這里用myeclipse實現服務器端。

新建一個web工程,這里要引入struct2相關,方法是:點擊新建的web工程郵件-》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;          }   } 


好了,下面選擇工程右鍵:run as->myeclipse server application:

 

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

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

出現如下 :

說明服務器端搭建成功。另外,本系統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;};};@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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;     }  } 


布局類很簡單就不寫了,可以自行下載源碼。運行Android程序:

運行不成功的注意網絡權限。

源碼下載:

服務器端

Android端

 

歡迎關注我和我的微信平台,謝謝


 

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com