1. 程式人生 > >接收http傳送的報文,並且列印處理

接收http傳送的報文,並且列印處理

1.首先建立一個servlet:

2.程式碼如下:

@WebServlet("/push") publicclass Test extends HttpServlet implements Servlet {     private static final long serialVersionUID = 1L;     public Test() {         // TODO Auto-generated constructor stub     }     protected void doGet(HttpServletRequest request, HttpServletResponse response
throws
 ServletException, IOException {         System.out.println("doGet");     }      protected void doPost(HttpServletRequest request, HttpServletResponse response)                throws ServletException, IOException {               try {                int len = request.getContentLength();         
                     //獲取HTTP請求的輸入流                      InputStream is = request.getInputStream();                      //已HTTP請求輸入流建立一個BufferedReader物件                      BufferedReader br = new BufferedReader(                     new InputStreamReader(is,"UTF-8"));                      //讀取HTTP請求內容
                     String buffer = null;                      StringBuffer sb = new StringBuffer();                      while ((buffer = br.readLine()) != null) {                      //在頁面中顯示讀取到的請求引數                          sb.append(buffer+"\n");                      }                     System.out.println("接收post傳送原始資料:\n"+sb.toString().trim());                     PrintWriter out = response.getWriter();                     StringBuffer stringBuffer = new StringBuffer("OK");                     out.write(stringBuffer.toString());                     out.flush();                     out.close();               } catch (Exception e) {               System.out.println("error"+e);         }     }