最近打算做一個酒店無線點餐的APP,需要將圖片放在服務器端的文件夾下,客戶端通過更新菜單按鈕可以獲得最新的菜品信息。要獲取圖片的信息首先需要得到圖片的名稱、對應的菜品價格以及圖片所在的路徑,因此需要在服務器端搜索文件夾下的所有圖片並將數據打包成JSON格式轉發給客戶端,具體格式為[{name="菜名",price=價格,path="文件路徑",category="菜品分類:如川菜、湘菜等"}]。服務器端采用servlet+jsp部署在Tomcat中,下面給出獲取文件目錄下所有圖片信息並封裝成JSON格式的代碼。服務器端圖片存儲的目錄如下所示。
package com.restaurant.utils; import java.io.File; public class JsonUtils { public static String getJson(String strPath) { StringBuilder builder = new StringBuilder(); builder.append('['); File file = new File(strPath); File[] fileList = file.listFiles(); for (int i = 0; i < fileList.length; i++) { if (fileList[i].isDirectory()) { File mFile = new File(fileList[i].getPath()); File[] mFileList = mFile.listFiles(); for (int j = 0; j < mFileList.length; j++) { String name = ""; String price = ""; String path = ""; String category = ""; String str = mFileList[j].getName(); String[] strList = str.split("\\$"); name = strList[0]; strList = strList[1].split("\\."); price = strList[0]; path = mFileList[j].getPath(); strList=path.split("\\\\"); path=""; for(String mstr:strList){ path=path+mstr+"\\\\"; } path=path.substring(0, path.length()-2); category = mFileList[j].getParent().substring( mFileList[j].getParent().lastIndexOf("\\") + 1); builder.append("{name:\"").append(name).append("\","); builder.append("price:").append(price).append(','); builder.append("path:\"").append(path).append("\","); builder.append("category:\"").append(category) .append("\"},"); } } } builder.deleteCharAt(builder.length() - 1); builder.append(']'); return builder.toString(); } }
創建一個Servlet文件在其doGet()方法中調用上面的getJson()方法,並將客戶端請求轉到一個JSP頁面,在JSP中通過EL表達式獲取出JSON字符串。
package com.restaurant.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.restaurant.utils.*; /** * Servlet implementation class UpdatePictureServlet */ @WebServlet("/UpdatePictureServlet") public class UpdatePictureServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static String strPath = "E:\\webTest\\Restaurant\\WebContent\\Pictures"; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub
request.setAttribute("json", JsonUtils.getJson(strPath)); request.getRequestDispatcher("/WEB-INF/page/jsondata.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub
} }
JSP頁面內容如下:
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}
將項目部署到服務器上,在瀏覽器中輸入:http://localhost:8080/Restaurant/UpdatePictureServlet回車之后的效果如下:
安卓客戶端通過HTTP協議獲取JSON數據,首先封裝一個PictureBean對象,該對象用於接收解析出來的JSON格式,同時創建和該對象對應的數據庫表,直接將對象列表存儲在SQLite數據庫中,方便本地讀取。下面是從服務器獲取JSON數據並存儲在PictureBean對象中的程序代碼:
package com.example.service; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.util.Log; import com.example.domain.PictureBean; import com.example.utils.StreamTool; public class UptadePictureService { public static List<PictureBean> getJSONPictures() throws Exception { String path = "http://192.168.1.103:8080/Restaurant/UpdatePictureServlet"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { InputStream inStream = conn.getInputStream(); return parseJSON(inStream); } return null; } /** * 解析JSON數據 * * @param inStream * @return
*/
private static List<PictureBean> parseJSON(InputStream inStream) throws Exception { List<PictureBean> Pictures = new ArrayList<PictureBean>(); byte[] data = StreamTool.read(inStream); String json = new String(data); Log.d("MainActivity", json); JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject jsonObject = array.getJSONObject(i); PictureBean picture = new PictureBean(jsonObject.getString("name"), jsonObject.getInt("price"), jsonObject.getString("path"), jsonObject.getString("category")); Pictures.add(picture); } return Pictures; } }
以上就是就是把圖片數據信息打包成JSON格式,以及安卓客戶端獲取圖片信息並保存為PictureBean對象的全部過程,有關數據庫方面的代碼比較簡單,這里不再貼出來。關於圖片的下載以及界面顯示部分的內容將在下一篇博客中進行介紹。