RESTful API实现APP订餐实例
生活随笔
收集整理的這篇文章主要介紹了
RESTful API实现APP订餐实例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
web網(wǎng)站如下:
客戶(hù)端APP查詢(xún)以及訂餐:
服務(wù)器端接收客戶(hù)訂單信息:
客戶(hù)端通過(guò)HTTP+JSON來(lái)調(diào)用這些服務(wù)。
首先是客戶(hù)端:
客戶(hù)端要用這些jar文件,不要忘記放進(jìn)去:
首先是HttpHelper.java
package my;import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;public class HttpHelper {//HTTP GET測(cè)試public static String doGet(String url) throws Exception{CloseableHttpClient httpclient=HttpClients.createDefault();HttpGet httpget=new HttpGet(url);CloseableHttpResponse response=httpclient.execute(httpget);try {StatusLine statusLine=response.getStatusLine();int status=statusLine.getStatusCode();if(status!=200) {throw new Exception("Http GET出錯(cuò):"+status+", "+statusLine.getReasonPhrase());}HttpEntity entity=response.getEntity();if(entity!=null) {long len=entity.getContentLength();if(len!=-1&&len<16384) {String replyText=EntityUtils.toString(entity);return replyText;}else {//Stream content out}}}finally {response.close();}return null;}//HTTP POST測(cè)試public static String doPost(String url,String reqText) throws Exception{CloseableHttpClient httpclient=HttpClients.createDefault();HttpPost httppost=new HttpPost(url);//上行數(shù)據(jù)StringEntity dataSent=new StringEntity(reqText,ContentType.create("text/plain","UTF-8"));httppost.setEntity(dataSent);CloseableHttpResponse response=httpclient.execute(httppost);try {StatusLine statusLine=response.getStatusLine();int status=statusLine.getStatusCode();if(status!=200) {throw new Exception("HTTP POST出錯(cuò):"+status+", "+statusLine.getReasonPhrase());}//下行數(shù)據(jù)HttpEntity dataRecv=response.getEntity();if(dataRecv!=null) {long len=dataRecv.getContentLength();if(len!=-1&&len<16384) {String replyText=EntityUtils.toString(dataRecv);return replyText;}else {//Stream content out}}}finally {response.close();}return null;}}然后是Booking.java
package my;import java.io.BufferedReader; import java.io.InputStreamReader;import org.json.JSONArray; import org.json.JSONObject;public class Booking {String baseUrl="http://127.0.0.1:8080/myweb";private void book(int foodId) throws Exception{JSONObject jsReq=new JSONObject();jsReq.put("foodId", foodId);jsReq.put("time", "2017-02-11 00:00:00");JSONObject jsClient=new JSONObject();jsClient.put("clientName", "朱小明");jsClient.put("clientPhone", "13156254789");jsClient.put("clientAddress", "XXX路XX號(hào)XX樓");jsReq.put("client", jsClient);String replyText=HttpHelper.doPost(baseUrl+"/api/Book", jsReq.toString());//應(yīng)答消息,錯(cuò)誤檢測(cè)JSONObject jsReply=new JSONObject(replyText);int error=jsReply.getInt("error"); String reason=jsReply.getString("reason");if(error!=0) {System.out.println("服務(wù)器返回錯(cuò)誤!error="+error+", reason:"+reason);return;}JSONObject data=jsReply.getJSONObject("data");System.out.println("訂單已下達(dá)!訂單號(hào)碼:"+data.getInt("bookId"));}//RESTful形式的APIprivate void list() throws Exception{String replyText=HttpHelper.doGet(baseUrl+"/api/ListFood");//錯(cuò)誤碼檢測(cè)JSONObject jsReply=new JSONObject(replyText);int error=jsReply.getInt("error");String reason=jsReply.getString("reason");if(error!=0) {System.out.println("服務(wù)器返回錯(cuò)誤!error"+error+" ,reason:"+reason);return;}//把電影列表顯示給用戶(hù)JSONArray data=jsReply.getJSONArray("data");for(int i=0;i<data.length();i++) {JSONObject m=data.getJSONObject(i);String line=String.format("商品號(hào):[%d] 商品名【%s】 價(jià)格: %s元 飲料:%s 商家:%s ", m.getInt("id"),m.getString("title"),m.getString("price"),m.getString("drink"),m.getString("merchant"));System.out.println(line);}}public void handleCommand(String[] argv) throws Exception{if(argv[0].equals("list")) {list();}else if(argv[0].equals("book")&&argv.length==2) {book(Integer.valueOf(argv[1]));}else {System.out.println("無(wú)效命令或無(wú)效參數(shù)!");}}//用戶(hù)主界面public void shell() throws Exception{InputStreamReader m=new InputStreamReader(System.in);BufferedReader reader=new BufferedReader(m);while(true) {System.out.print("\n>"); //輸入提示String nextline=reader.readLine();if(nextline==null) break;String[] argv=nextline.split(" ");if(argv.length==0) continue;if(argv[0].equals("quit")) break;try {handleCommand(argv);}catch(Exception e) {e.printStackTrace();}}reader.close();}public static void main(String[] args) {try {Booking t=new Booking();t.shell();}catch(Exception e) {e.printStackTrace();}}}服務(wù)器端:要使用json的jar
book.jsp代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>My JSP 'book.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body>This is my JSP page. <br></body> </html>list_food.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>菜單列表</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"><script src="jquery/jquery.js"></script><script src="bootstrap/js/bootstrap.min.js"></script><script src="jquery/jquery.json-2.3js"></script><script>function trace(msg){try{console.log(msg);}catch(err){}//頁(yè)面加載后的初始化工作$(document).ready(function(){});}</script></head><body><div class="container">外賣(mài)列表</div><table class="table"><tr><th>菜名</th><th>價(jià)格</th><th>飲料</th><th>商家</th></tr><tr><td> <a href="book.jsp?foodId=100001"> 脆皮雞 </a></td><td> 15 </td><td> 冰紅茶 </td><td> 美團(tuán) </td></tr><tr><td> <a href="book.jsp?foodId=10002"> 黃燜雞 </a></td><td> 18 </td><td> 雪碧 </td><td> 餓了嗎 </td></tr><tr><td> <a href="book.jsp?foodId=10003"> 重慶雞公煲 </a></td><td> 18 </td><td> 礦泉水 </td><td> 百度外賣(mài) </td></tr></table></body> </html>這個(gè)web.xml要做如下配置:
<?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><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>Book</servlet-name><servlet-class>my.BookServlet</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>ListFood</servlet-name><servlet-class>my.ListFoodServlet</servlet-class></servlet><servlet-mapping><servlet-name>Book</servlet-name><url-pattern>/api/Book</url-pattern></servlet-mapping><servlet-mapping><servlet-name>ListFood</servlet-name><url-pattern>/api/ListFood</url-pattern></servlet-mapping> <welcome-file-list><welcome-file>list_food.jsp</welcome-file></welcome-file-list> </web-app>關(guān)于java的class,從tcp stream讀取數(shù)據(jù)的文件
Util.java
package my;import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream;public class Util {// 從TCP Stream中讀取時(shí),要反復(fù)讀取,直接讀完public static String readAsText(InputStream streamIn, String charset) throws IOException {ByteArrayOutputStream cache = new ByteArrayOutputStream(4096); byte[] data = new byte[1024]; while (true){int len = streamIn.read(data);if(len < 0) // 連接已經(jīng)斷開(kāi)break;if(len == 0) // 數(shù)據(jù)未完continue;// 緩存起來(lái)cache.write(data, 0, len);if(cache.size() > 1024*16) // 上限, 最多讀取16KBbreak;} return cache.toString(charset);} }下面是兩個(gè)Servlet
一個(gè)是BookServlet.java
package my;import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.json.JSONObject;public class BookServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{// 讀取用戶(hù)請(qǐng)求String reqText = Util.readAsText(request.getInputStream(), "UTF-8"); JSONObject jsReq = new JSONObject(reqText);JSONObject client = jsReq.getJSONObject("client"); // 客戶(hù)的快遞地址String clientName = client.getString("clientName"); String clientPhone = client.getString("clientPhone"); String clientAddress = client.getString("clientAddress");int foodId = jsReq.getInt("foodId");String time = jsReq.getString("time");Date day=new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 構(gòu)造JSONJSONObject jsReply = new JSONObject();jsReply.put("error", 0);jsReply.put("reason", "OK");// 生成訂單號(hào) (模擬)int bookId = (int) (Math.random() * 1000);JSONObject data = new JSONObject();data.put("bookId", bookId);jsReply.put("data", data);System.out.println("客戶(hù)訂單:");System.out.println("訂單號(hào):"+bookId);System.out.println("商品號(hào):"+foodId);System.out.println("客戶(hù)名:"+clientName);System.out.println("客戶(hù)電話(huà):"+clientPhone);System.out.println("客戶(hù)地址:"+clientAddress);System.out.println("下單時(shí)間:"+df.format(day));String replyText = jsReply.toString();// 采用Content-Length方式byte[] outdata = replyText.getBytes("UTF-8");response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.setContentLength(outdata.length);OutputStream out = response.getOutputStream();out.write(outdata);out.close();}一個(gè)·是:ListFoodServlet.java
package my;import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.json.JSONArray; import org.json.JSONObject;public class ListFoodServlet extends HttpServlet {/*** Constructor of the object.*/public ListFoodServlet() {super();}/*** Destruction of the servlet. <br>*/public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//返回電影列表給用戶(hù) JSONArray movies = new JSONArray();JSONObject m1 = new JSONObject();m1.put("id", 100001);m1.put("title", "脆皮雞");m1.put("drink", "冰紅茶");m1.put("price", "15");m1.put("merchant", "美團(tuán)");movies.put(m1);JSONObject m2 = new JSONObject();m2.put("id", 100002);m2.put("title", "黃燜雞");m2.put("drink", "雪碧");m2.put("price", "18");m2.put("merchant", "餓了嗎");movies.put(m2);JSONObject m3 = new JSONObject();m3.put("id", 100003);m3.put("title", "重慶雞公煲");m3.put("drink", "礦泉水");m3.put("price", "18");m3.put("merchant", "百度外賣(mài)");movies.put(m3);JSONObject jsReply = new JSONObject();jsReply.put("error", 0); // 錯(cuò)誤碼,0表示成功jsReply.put("reason", "OK"); // 錯(cuò)誤描述jsReply.put("data", movies); // 數(shù)據(jù)String replyText = jsReply.toString();// 應(yīng)答: 為了方便用客戶(hù)端的解析, 采用Content-Length方式byte[] outdata = replyText.getBytes("UTF-8");response.setContentType("text/plain"); // Content-Typeresponse.setCharacterEncoding("UTF-8"); // charset response.setContentLength(outdata.length);// Content-LengthOutputStream out = response.getOutputStream();out.write(outdata);out.close();} }總結(jié)
以上是生活随笔為你收集整理的RESTful API实现APP订餐实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python创建百万个文件_python
- 下一篇: MySQL入门之创建、更新、修改、复制、