Java SE/Socket POST Request

Socket 을 이용하여 웹서버에 POST 요청 예제

Soul-Learner 2008. 1. 6. 22:05


import java.io.*;
import java.net.*;

public class SocketPOST {

  public static void main(String[] args) {
   //Sending a POST Request Using a Socket
   try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("홍길동", "UTF-8");
  
    // Create a socket to the host
    //String hostname = "hostname.com";
    String hostname = "localhost";
    int port = 80;
    InetAddress addr = InetAddress.getByName(hostname);
    Socket socket = new Socket(addr, port);
  
    // Send header
    String path = "/TestWeb/sample.jsp";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
    wr.write("POST "+path+" HTTP/1.0\r\n");
    wr.write("Content-Length: "+data.length()+"\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n");
  
    // Send data
    wr.write(data);
    wr.flush();
  
    // Get response
    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
    String line;
    while ((line = rd.readLine()) != null) {
     System.out.println(line);
    }
    wr.close();
    rd.close();
   } catch (Exception e) {
   }
  }
 }


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<%
 //request.setCharacterEncoding("UTF-8");
 String value1 = request.getParameter("key1");
 String value2 = request.getParameter("key2");

 out.println("This is server response.");
 out.println("key1="+value1);
 out.println("key2="+value2);
%>
</body>
</html>


SocketPOST.java 를 컴파일하고 위의 sample.jsp 파일을 포함한 Tomcat 을 기동한 후에 SocketPOST 파일을 실행하면 다음과 같은 결과를 확인할 수 있다.

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=E8CCB051A8EDF10E96DEF70DBEF65AA5; Path=/TestWeb
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 192
Date: Mon, 07 Jan 2008 06:48:47 GMT
Connection: close

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
This is server response.
key1=value1
key2=홍길동
</body>
</html>