티스토리 뷰

다른 업체와 API로 데이터를 주고 받아서 처리해야 하는데, 아직 협의는 안됐지만 아마도 JSON으로 하지 않을까 싶다.

그래서!!!

미리 테스트해보며 준비해보고자 구글링한 것을 적어야겠다.

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
48
49
50
51
52
53
54
55
56
57
58
59
   public static void main(String[] args) throws Exception {
        sendPostJson();
        sendGetJson();
    }
 
    public static void sendPostJson() throws Exception {
        //JSON 데이터 받을 URL 객체 생성
        URL url = new URL ("www.google.com");
        //HttpURLConnection 객체를 생성해 openConnection 메소드로 url 연결
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //전송 방식 (POST)
        con.setRequestMethod("POST");
        //application/json 형식으로 전송, Request body를 JSON으로 던져줌.
        con.setRequestProperty("Content-Type""application/json; utf-8");
        //Response data를 JSON으로 받도록 설정
        con.setRequestProperty("Accept""application/json");
        //Output Stream을 POST 데이터로 전송
        con.setDoOutput(true);
        //json data
        String jsonInputString = "{id : faker, game : lol }";
 
        //JSON 보내는 Output stream
        try(OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }
 
        //Response data 받는 부분
        try(BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            System.out.println(response.toString());
        }
    }
 
    public static void sendGetJson() throws Exception {
        URL url = new URL ("www.google.com");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type""application/json; utf-8");
        con.setRequestProperty("Accept""application/json");
 
        con.setRequestProperty("id""faker");
        con.setRequestProperty("game""lol");
 
        try(BufferedReader br = new BufferedReader(
                new InputStreamReader(con.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            System.out.println(response.toString());
        }
    }
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

GET/POST로 JSON을 넘기는 코드와 설명은 준비가 되었는데...

테스트를 하려면 새로 다른 서버를 파야하나 요즘 같은 세상에 다 있지 않을까...

해서 찾아본 결과 괜찮은 사이트가 있었다.

https://webhook.site

1) Edit 혹은 처음 만들 때, Response body를 지정해 코드가 제대로 전송이 됐는지 확인할 수 있다.

2) 우측 상단의 Copy를 클릭해 복사한 URL을 코드의 URL 객체에 넣는다.

3) JSON을 날려본다.

4) POST와 GET 모두 데이터가 잘 전송된걸 확인할 수 있다!

 

ps. 위에 사이트가 별로다 싶으면 

https://stackoverflow.com/questions/5725430/http-test-server-accepting-get-post-requests

여기에 다른 대안들이 많이 있으니 골라 쓰는 재미가 있다!

 

Reference

https://www.baeldung.com/httpurlconnection-post

https://bobr2.tistory.com/entry/HttpConnection-Get-Post-%EC%82%AC%EC%9A%A9%EB%B2%95

https://mytalkhome.tistory.com/855

댓글