[java] HTTP POST body data를 송/수신하는 서블릿 코드.(*.java, servlet code)

2022. 2. 14. 11:11Language/java

728x90
728x90

-HTTP POST body data send/recv servlet code.(echo server)

package http_post_servlet;

import java.io.*;
import java.io.PrintWriter;
import java.net.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Httpserver
 */
public class httpPostServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	/**
	 * Default constructor.
	 */
	public httpPostServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doPost() is Running...");

		InputStream in = null;
		BufferedReader reader = null;
		HttpURLConnection httpURLConnection = null;

		String recvMsg = null;
		String sendMsg = null;
		
		try {
			in = request.getInputStream();
			reader = new BufferedReader(new InputStreamReader(in, "utf-8"));

			System.out.println("read is Running...");

			StringBuffer fileData = new StringBuffer(1024);
			char[] buf = new char[1024];
			int numRead = 0;

			while ((numRead = reader.read(buf)) != -1) {
				fileData.append(buf, 0, numRead);
				System.out.println("append is Running...");
			}

			in.close();
			reader.close();

			recvMsg = fileData.toString();
			System.out.println("recvMsg : " + recvMsg);
			sendMsg = recvMsg;

		} catch (Exception e) {
		} finally {
			if (in != null)
				in.close();
			if (reader != null)
				reader.close();
		}

		try {
			
			response.setContentType("text/html);charset=euc-kr");
			PrintWriter out = response.getWriter();
			out.println(sendMsg);
			System.out.println("sendMsg : " + sendMsg);
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (httpURLConnection != null) {
					httpURLConnection.disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

-생성한 servlet WAS(JEUS 6.0 Fix#9) 디플로이 POSTMAN tool 사용하여, 데이터 /수신 출력 결과.(POSTMAN <-> WAS)

  • 송/수신 전문(JSON).
{
    "uid" : "0123456789",
    "datas" :
    {
        "object1" : "value1"
    }
}
  • WAS(JEUS 6.0 Fix#9) 출력 로그.
doPost() is Running...
read is Running...
append is Running...
recvMsg : {
	    "uid" : "0123456789",
	    "datas" :
	    {
	        "object1" : "value1"
	    }
}
sendMsg : {
	    "uid" : "0123456789",
	    "datas" :
	    {
	        "object1" : "value1"
	    }
}
  • 포스트맨 출력 결과.

 

728x90
728x90