본문 바로가기

프로그래밍/안드로이드

android 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>


한번 테스트를 해봐야 겠네요.

출처 : http://adsgear.tistory.com/56