->1.服务器端生成和发布json数据
1.1 新建web工程,并建立相应的servlet和数据模型以及dao等
1.2 通过查询数据库等方式获取到数据后,封装成json形式String数据,
以PrintWritter写入Response作用域,也可跳转至jsp页面形式
1.3 "contentType="text/plain; charset=UTF-8"
设置PrintWritter写入类型
1.4 发布工程
->2.android客户端获取并解析json数据
2.1 通过new URL(path).openconnection获取到HttpURLConnection,由该对象的
getInputStream()方法可获得InputStream
2.2 利用JSONArray解析json数据,将获取的Stream数据转换成String数据后,通过
new JSONArray(str)获得JSONArray,迭代获得每一个JSONObject,再获取相应对象数据
2.3 解析获得对象集合
【注】需要权限:<uses-permission android:name="android.permission.INTERNET"/>
【源代码如下:】
*/
/****************************************【源码】START**************************************************/
/* -------------------------- part1 服务器端 START------------------------------ */
//1.2 Service类 JSONServiceBean.java
//1.3 Servlet JsonTestServlet.java
//1.4 web.xml
/* -------------------------- part1 服务器端 END------------------------------ */
/* -------------------------- part2 Android客户端 START------------------------------ */
//2.1 JSONService.java
//2.2 MainActivity.java
//2.3 activity_main.xml
//2.4 main_list_item.xml
//2.5 AndroidManifest.xml
/* -------------------------- part2 Android客户端 END------------------------------ */
/****************************************【源码】END**************************
1.1 新建web工程,并建立相应的servlet和数据模型以及dao等
1.2 通过查询数据库等方式获取到数据后,封装成json形式String数据,
以PrintWritter写入Response作用域,也可跳转至jsp页面形式
1.3 "contentType="text/plain; charset=UTF-8"
设置PrintWritter写入类型
1.4 发布工程
->2.android客户端获取并解析json数据
2.1 通过new URL(path).openconnection获取到HttpURLConnection,由该对象的
getInputStream()方法可获得InputStream
2.2 利用JSONArray解析json数据,将获取的Stream数据转换成String数据后,通过
new JSONArray(str)获得JSONArray,迭代获得每一个JSONObject,再获取相应对象数据
2.3 解析获得对象集合
【注】需要权限:<uses-permission android:name="android.permission.INTERNET"/>
【源代码如下:】
*/
/****************************************【源码】START**************************************************/
/* -------------------------- part1 服务器端 START------------------------------ */
//1.1 数据模型 News.java
public class News {
/** 新闻id */
private Integer newId;
/** 新闻标题 */
private String title;
/** 持续时间 */
private Integer timelength;
// Some constructs
// Getter and Setter
}
//1.2 Service类 JSONServiceBean.java
public class JSONServiceBean implements JSONService {
public List<News> getNewsByJson() {
List<News> news = new ArrayList<News>();
news.add(new News(106, "[json] 今天有雨,戴珊出门!", 20));
news.add(new News(107, "[json] 中国好声音即将开幕!", 35));
news.add(new News(108, "[json] CCTV5邀您共赏世界杯!", 15));
news.add(new News(109, "[json] Goole开创移动新时代!", 53));
news.add(new News(110, "[json] 中国南海事件落幕!", 63));
return news;
}
}
//1.3 Servlet JsonTestServlet.java
public class JsonTestServlet extends HttpServlet {
private JSONServiceBean serviceBean = new JSONServiceBean();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<News> news = serviceBean.getNewsByJson();
// 格式:[{id:1,title:"fds",timelength:23},{id:1,title:"fds",timelength:23}]
StringBuilder sBuilder = new StringBuilder();
sBuilder.append('[');
for(News n : news){
sBuilder.append('{')
.append("newId:").append(n.getNewId().toString()).append(',')
.append("title:\"").append(n.getTitle()).append("\",")
.append("timelength:").append(n.getTimelength().toString())
.append("},");
}
sBuilder.deleteCharAt(sBuilder.length() - 1);
sBuilder.append(']');
// request.setAttribute("news", sBuilder.toString());
// request.getRequestDispatcher("/WEB-INF/page/json_news.jsp");
response.setContentType("text/plain; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(sBuilder.toString());
out.close();
}
}
//1.4 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<display-name>JsonTestServlet</display-name>
<servlet-name>JsonTestServlet</servlet-name>
<servlet-class>cn.gzu.androidtest.servlet.JsonTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JsonTestServlet</servlet-name>
<url-pattern>/servlet/JsonTestServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
/* -------------------------- part1 服务器端 END------------------------------ */
/* -------------------------- part2 Android客户端 START------------------------------ */
//2.1 JSONService.java
public class JSONService {
public static List<News> getNewsList() throws Exception {
String netPath = "http://10.0.2.2:8080/AndroidDataTest/servlet/JsonTestServlet";
HttpURLConnection conn = (HttpURLConnection) new URL(netPath).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream xmlStream = conn.getInputStream();
return readNewsFromStream(xmlStream);
}
return null;
}
private static List<News> readNewsFromStream(InputStream is) throws Exception{
List<News> news = new ArrayList<News>();
byte[] data = NetResourceUtil.StreamTool(is);
String jsonData = new String(data);
JSONArray jsonArray = new JSONArray(jsonData);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int newId = jsonObject.getInt("newId");
String title = jsonObject.getString("title");
int timelength = jsonObject.getInt("timelength");
news.add(new News(newId,title,timelength));
}
return news;
}
}
//2.2 MainActivity.java
public class MainActivity extends Activity {
private ListView mainList;
private List<News> news;
private MyListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView main = (TextView) findViewById(R.id.main_content);
mainList = (ListView) findViewById(R.id.maib_list);
}
public void XMLTest(View v){
xmlTest();
}
public void JSONTest(View v){
try {
news = JSONService.getNewsList();
System.out.println("news.size();"+news.size());
adapter = new MyListAdapter();
mainList.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
private void xmlTest() {
}
private class MyListAdapter extends BaseAdapter{
@Override
public int getCount() {
return news.size();
}
@Override
public Object getItem(int position) {
return news.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView!=null){
holder = (ViewHolder) convertView.getTag();
}else{
holder = new ViewHolder();
convertView = View.inflate(getBaseContext(), R.layout.main_list_item, null);
holder.testText1 = (TextView) convertView.findViewById(R.id.main_content_1);
holder.testText2 = (TextView) convertView.findViewById(R.id.main_content_2);
holder.testText3 = (TextView) convertView.findViewById(R.id.main_content_3);
convertView.setTag(holder);
}
News newn = news.get(position);
holder.testText1.setText(String.valueOf(newn.getNewId()));
holder.testText2.setText(newn.getTitle());
holder.testText3.setText(String.valueOf(newn.getTimelength()));
return convertView;
}
class ViewHolder{
TextView testText1;
TextView testText2;
TextView testText3;
}
}
}
//2.3 activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical" >
<TextView
android:id="@+id/main_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="XML"
android:onClick="XMLTest"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JSON"
android:onClick="JSONTest"/>
</LinearLayout>
<ListView
android:id="@+id/maib_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
//2.4 main_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/main_content_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_gravity="center_vertical"
android:text="@string/hello_world" />
<TextView
android:id="@+id/main_content_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_gravity="center_vertical"
android:text="@string/hello_world" />
<TextView
android:id="@+id/main_content_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_gravity="center_vertical"
android:text="@string/hello_world" />
</LinearLayout>
//2.5 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.gzu.xmlparsertest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="android.test.runner" />
<activity
android:name="cn.gzu.xmlparsertest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="cn.gzu.xmlparsertest" />
</manifest>
/* -------------------------- part2 Android客户端 END------------------------------ */
/****************************************【源码】END**************************