work/Java

Java로 HTTP Post 발송

토익귀족 2023. 5. 25. 09:40
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
40
41
42
43
44
45
46
47
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Main {
    public static void main(String[] args) {
        String url = "http://example.com/post-endpoint"// 전송하려는 URL
        String jsonMessage = "{\"key1\":\"value1\",\"key2\":\"value2\"}"// 전송할 JSON 메시지
 
        try {
            URL postUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type""application/json");
            connection.setDoOutput(true);
 
            DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(jsonMessage);
            outputStream.flush();
            outputStream.close();
 
            int responseCode = connection.getResponseCode();
 
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
 
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
 
                reader.close();
                System.out.println("응답 내용: " + response.toString());
            } else {
                System.out.println("HTTP 요청 실패. 응답 코드: " + responseCode);
            }
 
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
cs