学习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程序:
执行不成功的注意网络权限。
源代码下载:
?
欢迎关注我和我的微信平台,谢谢
?
?