본문 바로가기

Java SE/URLConnection POST

URLConnection을 이용하여 웹서버에 POST방식요청 예제


import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class URLConnectionPOST {
 public static void main(String[] args) {
     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");
    
         // Send data
         URL url = new URL("http://localhost:80/TestWeb/sample.jsp");
         URLConnection conn = url.openConnection();
         // If you invoke the method setDoOutput(true) on the URLConnection, it will always use the POST method.
         conn.setDoOutput(true);
         OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
         wr.write(data);
         wr.flush();
    
         // Get the response
         BufferedReader rd = new BufferedReader(new InputStreamReader(conn.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>

URLConnectionPOST.java를 컴파일하고 위의 sample.jsp 를 포함한 Tomcat을 기동한 후에 URLConnectionPOST를 실행하면 다음과 같은 결과를 확인할 수 있다.
<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>