반응형
출처사이트 : https://nine01223.tistory.com/m/256
HttpURLConnection을 이용해서 POST 호출을 하려면
다소 복잡한 과정이 필요하다.
하지만 다음과 같은 심플한 과정을 통해서(정형화된 과정을 통해)
쉽게 호출할 수 있다!
자주 사용하는 코드이므로 유용하게 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import java.io.*;
import java.net.*;
import java.util.*;
class Test {
public static void main(String[] args) throws Exception {
Map<String,Object> params = new LinkedHashMap<>(); // 파라미터 세팅
params.put("name", "james");
params.put("email", "james@example.com");
params.put("reply_to_thread", 10394);
params.put("message", "Hello World");
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet()) {
if(postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes); // POST 호출
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String inputLine;
while((inputLine = in.readLine()) != null) { // response 출력
System.out.println(inputLine);
}
in.close();
}
}
|
반응형
'웹개발 > jsp' 카테고리의 다른 글
webSocket 웹 채팅 만들기 (0) | 2022.02.17 |
---|---|
xss 방지 (0) | 2022.02.17 |
HttpSessionListener 이용 중복 로그인 방지 (0) | 2022.02.17 |
스프링 세션 동작 원리 (0) | 2022.02.17 |
세션 생성 및 제거. (0) | 2022.02.17 |
댓글