在web端和android端通过JSON格式实现数据交互

我的web端服务器使用tomcat,数据库是用的Oracle,利用struts2实现页面跳转。采用MVC模式,有vo层,dao层,和Service层,在Action中调用Service中的方法,进行增删该查。在数据传输时,android端需要导入Apache提供的jar包:org.json.jar

我只写出Action类的代码:

public class NewsAction extends ActionSupport {

	private News news;

	private int pageNo;
	private int pageSize;

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public String insertPre() throws Exception {
		List<NewsType> all = ServiceFactory.getINewsServiceInstance()
				.insertPre();

		JSONArray array = new JSONArray();

		Iterator<NewsType> iter = all.iterator();
		while (iter.hasNext()) {
			NewsType t = iter.next();

			JSONObject obj = new JSONObject();
			obj.put("tid", t.getTid());
			obj.put("tname", t.getTname());

			array.put(obj);
		}

		HttpServletResponse response = ServletActionContext.getResponse();

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		out.print(array);
		out.close();

		return null;
	}

	public String list() throws Exception {
		Map<String, Object> map = ServiceFactory.getINewsServiceInstance()
				.list(pageNo, pageSize);
		List<News> allNews = (List<News>) map.get("allNews");
		int count = (Integer) map.get("count");

		JSONObject root = new JSONObject();

		JSONArray array = new JSONArray();

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

		Iterator<News> iter = allNews.iterator();
		while (iter.hasNext()) {
			News n = iter.next();

			JSONObject obj = new JSONObject();
			obj.put("id", n.getId());
			obj.put("title", n.getTitle());
			obj.put("content", n.getContent());
			obj.put("pubDate", sf.format(n.getPubDate()));
			obj.put("typeId", n.getTypeId());

			array.put(obj);
		}
<pre name="code" class="java">

 在android端写了一个Util工具类,专门用来与web端进行数据交互 

public class NetworkUtils {

	private static final String URL_BASE = "http://192.168.2.106:8080/AndroidNewsDemo/";

	public static final String GET_ALL_NEWS_TYPE_URL = URL_BASE
			+ "news!insertPre.action";

	public static final String NEWS_INSERT_URL = URL_BASE
			+ "news!insert.action";

	public static final String NEWS_LIST_URL = URL_BASE + "news!list.action";

	public static String getDataByUrl(String urlStr) throws Exception {
		URL url = new URL(urlStr);
		URLConnection conn = url.openConnection();
		InputStream is = conn.getInputStream();

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String line = null;
		StringBuilder builder = new StringBuilder();

		while ((line = reader.readLine()) != null) {
			builder.append(line);
		}
		reader.close();

		return builder.toString();
	}

	public static JSONArray getJSONArrayByUrl(String urlStr) throws Exception {
		return new JSONArray(getDataByUrl(urlStr));
	}

	public static JSONObject getJSONObjectByUrl(String urlStr) throws Exception {
		return new JSONObject(getDataByUrl(urlStr));
	}

	public static String postDataByUrl(String url, Map<String, String> params)
			throws Exception {
		// 使用HttpClient来完成post提交
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);

		// 准备参数集合
		List<NameValuePair> allParams = new ArrayList<NameValuePair>();

		Iterator<Entry<String, String>> iter = params.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = iter.next();
			allParams.add(new BasicNameValuePair(entry.getKey(), entry
					.getValue()));
		}

		// 设置参数
		post.setEntity(new UrlEncodedFormEntity(allParams));

		HttpResponse response = client.execute(post);

		return EntityUtils.toString(response.getEntity());
	}

	public static JSONArray postJSONArrayByUrl(String urlStr,
			Map<String, String> params) throws Exception {
		return new JSONArray(postDataByUrl(urlStr, params));
	}

	public static JSONObject postJSONObjectByUrl(String urlStr,
			Map<String, String> params) throws Exception {
		return new JSONObject(postDataByUrl(urlStr, params));
	}
}
在Activity类中调用这个NetworkUtils类中的方法就可以实现数据传输。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值