Java를 사용한 POST 방식 데이터 전송 및 응답 처리하기
1 public static void main(String[] args) {
2 try {
3 //연결
4 URL url = new URL("http://www.example.com/post.php");
5 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
6 conn.setDoOutput(true);
7 conn.setRequestMethod("POST");
8 conn.setRequestProperty("Accept-Language", "ko-kr,ko;q=0.8,en-us;q=0.5,en;q=0.3");
9
10 //데이터
11 String param = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode("??", "UTF-8");
12 param += "&" + URLEncoder.encode("age", "UTF-8") + "=" + URLEncoder.encode("??", "UTF-8");
13
14 //전송
15 OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
16 osw.write(param);
17 osw.flush();
18
19 //응답
20 BufferedReader br = null;
21 br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
22 String line = null;
23 while ((line = br.readLine()) != null) {
24 System.out.println(line);
25 }
26
27 //닫기
28 osw.close();
29 br.close();
30 } catch (MalformedURLException e) {
31 e.printStackTrace();
32 } catch (ProtocolException e) {
33 e.printStackTrace();
34 } catch (UnsupportedEncodingException e) {
35 e.printStackTrace();
36 } catch (IOException e) {
37 e.printStackTrace();
38 }
39 }
40 }
댓글
댓글 쓰기