1. 程式人生 > >【nodemcu】後臺接受nodemcu資料,做的一個小demo,不考慮其他

【nodemcu】後臺接受nodemcu資料,做的一個小demo,不考慮其他

/*public static String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
 
		// 讀取請求內容
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		
		return sb.toString();
	}*/
	public static JSONObject receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
		 
		// 讀取請求內容
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		
		return JSONObject.parseObject(sb.toString());
	}
package com.pillow.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.pillow.util.JsonReader;




public class Getinfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Statement stmt = null;
	private int flag;
 
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * 執行Post方法
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Connection conn=null;
		PrintWriter out=response.getWriter();
		try{
			Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/pillow?user=root&password=密碼");
			stmt = conn.createStatement();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			out.println("404");
		}
		JSONObject obj = JsonReader.receivePost(request);
		//String obj=JsonReader.receivePost(request);
		try {
			String s="insert into test values('"+obj+"')";
			flag = stmt.executeUpdate(s);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		out.print(flag);
	}
		
}