Servlet接收http请求

2021-03-19 04:27

阅读:634

标签:att   catch   ati   package   system   ack   obj   objects   close   

接收对象:

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请求

标签:att   catch   ati   package   system   ack   obj   objects   close   

原文地址:https://www.cnblogs.com/JAYIT/p/12762274.html


评论


亲,登录后才可以留言!