RESTful API实现APP订餐实例
发布日期:2021-06-30 10:51:51 浏览次数:2 分类:技术文章

本文共 10766 字,大约阅读时间需要 35 分钟。

web网站如下:

客户端APP查询以及订餐:

服务器端接收客户订单信息:

客户端通过HTTP+JSON来调用这些服务。

首先是客户端:

客户端要用这些jar文件,不要忘记放进去:

首先是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测试	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出错:"+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测试	public static String doPost(String url,String reqText) throws Exception{		CloseableHttpClient httpclient=HttpClients.createDefault();		HttpPost httppost=new HttpPost(url);				//上行数据		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出错:"+status+", "+statusLine.getReasonPhrase());			}						//下行数据			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号XX楼");		jsReq.put("client", jsClient);				String replyText=HttpHelper.doPost(baseUrl+"/api/Book", jsReq.toString());				//应答消息,错误检测		JSONObject jsReply=new JSONObject(replyText);		int error=jsReply.getInt("error"); 		String reason=jsReply.getString("reason");		if(error!=0) {			System.out.println("服务器返回错误!error="+error+", reason:"+reason);			return;		}		JSONObject data=jsReply.getJSONObject("data");		System.out.println("订单已下达!订单号码:"+data.getInt("bookId"));	}		//RESTful形式的API	private void list() throws Exception{		String replyText=HttpHelper.doGet(baseUrl+"/api/ListFood");				//错误码检测		JSONObject jsReply=new JSONObject(replyText);		int error=jsReply.getInt("error");		String reason=jsReply.getString("reason");		if(error!=0) {			System.out.println("服务器返回错误!error"+error+" ,reason:"+reason);			return;		}				//把电影列表显示给用户		JSONArray data=jsReply.getJSONArray("data");		for(int i=0;i
"); //输入提示 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(); } }}

服务器端:要使用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+"/";%>              My JSP 'book.jsp' starting page    	
This is my JSP page.

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+"/";%>              菜单列表    	
外卖列表
菜名 价格 饮料 商家
脆皮鸡 15 冰红茶 美团
黄焖鸡 18 雪碧 饿了吗
重庆鸡公煲 18 矿泉水 百度外卖

这个web.xml要做如下配置:

This is the description of my J2EE component
This is the display name of my J2EE component
Book
my.BookServlet
This is the description of my J2EE component
This is the display name of my J2EE component
ListFood
my.ListFoodServlet
Book
/api/Book
ListFood
/api/ListFood
list_food.jsp

关于java的class,从tcp stream读取数据的文件

Util.java

package my;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class Util {	// 从TCP Stream中读取时,要反复读取,直接读完		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) // 连接已经断开	        		break;	        	if(len == 0) // 数据未完	        		continue;	        	// 缓存起来	        	cache.write(data, 0, len);	        		        	if(cache.size() > 1024*16) // 上限, 最多读取16KB	        		break;	        }       	        return cache.toString(charset);		}}

下面是两个Servlet

一个是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{		// 读取用户请求		String reqText = Util.readAsText(request.getInputStream(), "UTF-8");	 	    JSONObject jsReq = new JSONObject(reqText);	    	    JSONObject client = jsReq.getJSONObject("client"); // 客户的快递地址	    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"); 	    		// 构造JSON		JSONObject jsReply = new JSONObject();		jsReply.put("error", 0);		jsReply.put("reason", "OK");				// 生成订单号 (模拟)		int bookId = (int) (Math.random() * 1000);		JSONObject data = new JSONObject();		data.put("bookId", bookId);		jsReply.put("data", data);			    System.out.println("客户订单:");	    System.out.println("订单号:"+bookId);	    System.out.println("商品号:"+foodId);	    System.out.println("客户名:"+clientName);	    System.out.println("客户电话:"+clientPhone);	    System.out.println("客户地址:"+clientAddress);	    System.out.println("下单时间:"+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();	}

一个·是: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. 
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * 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 { //返回电影列表给用户 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", "美团"); 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", "百度外卖"); movies.put(m3); JSONObject jsReply = new JSONObject(); jsReply.put("error", 0); // 错误码,0表示成功 jsReply.put("reason", "OK"); // 错误描述 jsReply.put("data", movies); // 数据 String replyText = jsReply.toString(); // 应答: 为了方便用客户端的解析, 采用Content-Length方式 byte[] outdata = replyText.getBytes("UTF-8"); response.setContentType("text/plain"); // Content-Type response.setCharacterEncoding("UTF-8"); // charset response.setContentLength(outdata.length);// Content-Length OutputStream out = response.getOutputStream(); out.write(outdata); out.close(); }}

转载地址:https://it1995.blog.csdn.net/article/details/79316123 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Filter的基本用法一
下一篇:Apache HttpComponents在App里访问HTTP服务

发表评论

最新留言

很好
[***.229.124.182]2024年04月26日 06时53分25秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章