티스토리 뷰
다른 업체와 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 객체 생성
//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");
}
//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 {
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을 넘기는 코드와 설명은 준비가 되었는데...
테스트를 하려면 새로 다른 서버를 파야하나 요즘 같은 세상에 다 있지 않을까...
해서 찾아본 결과 괜찮은 사이트가 있었다.
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
'JAVA' 카테고리의 다른 글
Date, Calendar 대신 LocalDate (0) | 2021.05.03 |
---|---|
List.sort(Comparator) - 숫자 정렬 (1, 2...) / 문자 + 숫자 정렬 (A01, A02...) (0) | 2020.11.29 |
이진탐색(Binary Search)을 활용해 효율적으로 서치하기 (0) | 2018.12.10 |
이중for문, 중첩for문, 중첩된 반복문 활용하기 (0) | 2018.11.21 |
예외 처리 (나중에 더 추가해야할듯) (0) | 2018.11.06 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- FrogJmp
- json
- 알고리즘
- 완주하지 못한 선수
- 기능개발
- 프로그래머스
- 124 나라의 숫자
- codility
- 최솟값
- 맵 api
- 노션트렐로광고X
- 예매 알림
- 더 나은 내일
- cgv
- 파이팅코리아
- API
- K번째수
- 문자열 내 마음대로 정렬하기
- AWS
- 객체지향과 디자인패턴
- Spring
- 자바
- 타겟 넘버
- 안드로이드 스튜디오
- 카카오인턴
- 스프링 부트
- 다음 맵 api
- 텔레그램
- 쇠막대기
- java
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함