Servlet接收http请求
Posted jayit
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet接收http请求相关的知识,希望对你有一定的参考价值。
接收对象:
package web; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/testObject") public class TestObjectServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reqBody = this.streamTostring(request.getInputStream(),"utf-8"); System.out.println("reqBody:"+reqBody); PrintWriter out = response.getWriter(); out.write("ok"); out.flush(); out.close(); } private String streamTostring(InputStream stream,String charset) throws UnsupportedEncodingException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int len; byte[] bytes = new byte[1024]; try { while ((len = stream.read(bytes)) != -1) { byteArrayOutputStream.write(bytes, 0, len); } } catch (IOException e) { e.printStackTrace(); } return byteArrayOutputStream.toString(charset); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理dopst请求"); this.doGet(request, response); } }
接收参数:
package web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/test") public class TestServlet extends HttpServlet{ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); System.out.println("receive name:"+name); PrintWriter out = response.getWriter(); out.write("name:"+name); out.flush(); out.close(); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理dopst请求") ; this.doGet(request, response); } }
以上是关于Servlet接收http请求的主要内容,如果未能解决你的问题,请参考以下文章