android和j2ee服務器 進行JSON 數據傳輸模板

->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.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**************************
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章