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

来源:互联网 发布:gt designer3数据版本 编辑:程序博客网 时间:2024/06/06 02:15

我的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类中的方法就可以实现数据传输。


0 0
原创粉丝点击