最近比较忙,没什么时间写博客,现在以后多补补吧,这次写的是安卓客户端上传和下载网络数据
原理很简单,使用JDBC读取数据库数据,并在网页输出XML文件;安卓客户端获取XML文件进行解析(这里使用的是PULL方式)
先看下后台和Android客户端代码的结构:
Web后台代码:
1、Model
package com.homework.schoolnews; public class Schoolnews { private int id; private String title; private String content; //内容 private String shareDate; //分享时间 private String pictureuri; //图片路径 private String shareperson;//分享人 public Schoolnews(int id, String title,String content, String shareDate, String pictureuri, String shareperson) { super(); this.id = id; this.title = title; this.content = content; this.shareDate = shareDate; this.pictureuri = pictureuri; this.shareperson = shareperson; } public Schoolnews() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getShareDate() { return shareDate; } public void setShareDate(String shareDate) { this.shareDate = shareDate; } public String getPictureuri() { return pictureuri; } public void setPictureuri(String pictureuri) { this.pictureuri = pictureuri; } public String getShareperson() { return shareperson; } public void setShareperson(String shareperson) { this.shareperson = shareperson; } }
package myservice; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class JDBCService { private java.sql.Connection connection=null; private java.sql.Statement statement=null; private PreparedStatement preparedStatement=null; private ResultSet resultSet=null; private String className="com.mysql.jdbc.Driver"; //MySQL数据库链接 private String url="jdbc:mysql://localhost:3306/schoolnews?user=root&password=123456"; //取得数据库连接 public java.sql.Connection getConnection(){ try { Class.forName(className).newInstance(); connection=DriverManager.getConnection(url); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return connection; } //关闭数据库 public void close(){ try { //注意关闭顺序 if (resultSet!=null) resultSet.close(); if (statement!=null) statement.close(); if (preparedStatement!=null) preparedStatement.close(); if (connection!=null) connection.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } //查询并返回结果集 public ResultSet query(String sql){ try { connection=getConnection(); statement=connection.createStatement(); resultSet=statement.executeQuery(sql); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return resultSet; } public void add(String sql){ try { connection=getConnection(); statement=connection.createStatement(); statement.execute(sql); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
package myservice; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import model.Schoolnews; public class SchoolNewsXML { public List<Schoolnews> getSchoolNews() throws SQLException { JDBCService jDBCService = new JDBCService(); List<Schoolnews> snews = new ArrayList<Schoolnews>(); Schoolnews schoolnews = null; ResultSet resultSet = jDBCService.query("select * from t_snews"); while (resultSet.next()) { schoolnews = new Schoolnews(); schoolnews.setTitle(resultSet.getString(2)); schoolnews.setContent(resultSet.getString(3)); schoolnews.setShareDate(resultSet.getString(4)); schoolnews.setShareperson(resultSet.getString(5)); schoolnews.setPictureuri(resultSet.getString(6)); snews.add(schoolnews); } return snews; } }
package snewsservlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Schoolnews; import myservice.SchoolNewsXML; public class ServletForXML extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private SchoolNewsXML schoolNewsXML=new SchoolNewsXML(); public ServletForXML() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Schoolnews> snews = null; try { snews = schoolNewsXML.getSchoolNews(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("snews", snews); String path="/index.jsp"; request.getRequestDispatcher(path); ServletContext application =this.getServletContext(); RequestDispatcher rd=application.getRequestDispatcher(path); //跳转 rd.forward(request,response); } public void init() throws ServletException { // Put your code here } }
<%@ page language="java" contentType="text/xml;charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><?xml version="1.0" encoding="UTF-8"?> <Schoolnewses><c:forEach items="${snews}"var="Schoolnews"> <Schoolnews id="${Schoolnews.id}"> <title>${Schoolnews. title}</title> <content>${Schoolnews.content}</content> <sharedate>${Schoolnews.shareDate}</sharedate> <shareperson>${Schoolnews.shareperson}</shareperson> <pictureuri>${Schoolnews.pictureuri}</pictureuri> </Schoolnews> </c:forEach> </Schoolnewses>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <servlet> <servlet-name>ServletForXML</servlet-name> <servlet-class>snewsservlet.ServletForXML</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>AddsnewsServlet</servlet-name> <servlet-class>snewsservlet.AddsnewsServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletForXML</servlet-name> <url-pattern>/servlet/ServletForXML</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>AddsnewsServlet</servlet-name> <url-pattern>/servlet/AddsnewsServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
接下来是在Android里面获取并解析xml,以下是主要代码,Activity那些就不贴出来了,主要核心是获取xml和解析xml
8、SchoolNewsService
package com.homework.schoolnews; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.util.Xml; public class SchoolNewsService { public static List<Schoolnews> getSchoolNews() throws MalformedURLException, IOException, XmlPullParserException { String path = "http://172.19.55.121:8080/androidHomework/servlet/ServletForXML"; HttpURLConnection con = (HttpURLConnection) new URL(path) .openConnection(); con.setConnectTimeout(15000); con.setRequestMethod("GET"); int i=con.getResponseCode(); if(i==200){ InputStream in = con.getInputStream(); return parseXML(in); } return null; } /* * pull方法解析xml */ private static List<Schoolnews> parseXML(InputStream in) throws XmlPullParserException, IOException { List<Schoolnews> snews = null; Schoolnews schoolnews = null; XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(in, "UTF-8"); int event = pullParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { switch (event) { case XmlPullParser.START_DOCUMENT: snews = new ArrayList<Schoolnews>(); break; case XmlPullParser.START_TAG: if ("Schoolnews".equals(pullParser.getName())) { int id = new Integer(pullParser.getAttributeValue(0)); schoolnews = new Schoolnews(); schoolnews.setId(id); } if ("title".equals(pullParser.getName())) { schoolnews.setTitle(pullParser.nextText()); } if ("content".equals(pullParser.getName())) { schoolnews.setContent(pullParser.nextText()); } if ("sharedate".equals(pullParser.getName())) { schoolnews.setShareDate(pullParser.nextText()); } if ("shareperson".equals(pullParser.getName())) { schoolnews.setShareperson(pullParser.nextText()); } if ("pictureuri".equals(pullParser.getName())) { schoolnews.setPictureuri(pullParser.nextText()); } break; case XmlPullParser.END_TAG: if ("Schoolnews".equals(pullParser.getName())) { snews.add(schoolnews); schoolnews = null; } break; } event = pullParser.next(); } return snews; } }
安卓获取并显示数据://2013-08-09 添加-Mr_Tank_
package com.homework.schoolnews; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.homew.shouldnews.R; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.*; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageButton bt_add = (ImageButton) this.findViewById(R.id.snews_add); find(); //添加校园新鲜事 bt_add.setOnClickListener(new ImageButton.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(MainActivity.this, AddsnewsActivity.class); startActivity(intent); } }); } private void find(){ final ListView lv = (ListView) this.findViewById(R.id.snews_listView); try { List<Schoolnews> snews = SchoolNewsService.getSchoolNews(); List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for (Schoolnews schoolnews : snews) { HashMap<String, Object> item = new HashMap<String, Object>(); item.put("id", schoolnews.getId()); item.put("title", schoolnews.getTitle()); item.put("content", schoolnews.getContent()); item.put("sharedate", schoolnews.getShareDate()); item.put("shareperson", schoolnews.getShareperson()); item.put("pictureuri", schoolnews.getPictureuri()); data.add(item); } SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.snews, new String[] { "title", "sharedate", "shareperson", "content" }, new int[] { R.id.snews_title, R.id.snews_shareTime, R.id.snews_writer, R.id.snews_content }); lv.setAdapter(adapter); } catch (Exception ex) { } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
效果:
数据上传:
package com.homework.schoolnews; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class AddsnewsService { // 静态方法 public static boolean save(String title, String content, String shareperson) throws MalformedURLException, IOException { String path = "http://172.19.55.121:8080/androidHomework/servlet/AddsnewsServlet?title=" +URLEncoder.encode(title, "UTF-8")+"&snewscontent=" +URLEncoder.encode(content, "UTF-8")+"&shareperson="+URLEncoder.encode(shareperson, "UTF-8"); /*bug *用以下方法装配path里有点问题 ,shareperson,上传到服务器的时候为null. */ // Map<String, String> params = new HashMap<String, String>(); // // params.put("title", title); // params.put("snewscontent", content); // params.put("shareperson", shareperson); // // StringBuilder sb = new StringBuilder(path); // 装配path // for (Map.Entry<String, String> entry : params.entrySet()) { // // 获取键 // sb.append(entry.getKey()).append("="); // sb.append(URLEncoder.encode(entry.getValue(), "UTF-8")); // sb.append("&"); // } // 删除装配path时多装配的&字符 //sb.deleteCharAt(sb.length() - 1); HttpURLConnection con = (HttpURLConnection) new URL(path) .openConnection(); con.setConnectTimeout(15000); con.setRequestMethod("GET"); con.setDoOutput(true);// 允许对外传输数据 byte[] pathdata = path.toString().getBytes(); // 设置通用的请求属性 // con.setRequestProperty("accept", "*/*"); // con.setRequestProperty("connection", "Keep-Alive"); // con.setRequestProperty("user-agent", // "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // // con.setRequestProperty("Content-Length", pathdata.length + ""); // con.connect(); OutputStream out = con.getOutputStream(); out.write(pathdata); out.flush(); if (con.getResponseCode() == 200) { return true; } return false; } }