最近打算做一个酒店无线点餐的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对象的全部过程,有关数据库方面的代码比较简单,这里不再贴出来。关于图片的下载以及界面显示部分的内容将在下一篇博客中进行介绍。