java url통신하여 json파라미터 받아 map으로리턴하기!

2021. 1. 21. 14:39개발하는중/java

728x90
반응형

java 에서 url 통신을 하는 경우 url통신하여 받는 데이터가 json형식 일때 파싱 하여 map에 담아 쓸수 있는 로직입니다.

음 코드 짠지는 좀되가지고...구글에서 검색하며 조합하여 테스트 해본겁니다.!

일단 테스트 해보려면 json형태의 파라미터를 던저 줄수 있는 url이 필요합니다.

 

 

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
     public Map<String, Object> URLCorrespondence(String pUrl) throws Exception{
          
          URL url = new URL(pUrl);
          Map<String, Object> map = new HashMap<String, Object>();
          // 문자열로 URL 표현
          System.out.println("URL :" + url.toExternalForm());
          
          // HTTP Connection 구하기 
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          
          // 요청 방식 설정 ( GET or POST or .. 별도로 설정하지않으면 GET 방식 )
          conn.setRequestMethod("GET"); 
          
          // 연결 타임아웃 설정 
          conn.setConnectTimeout(3000); // 3초 
          // 읽기 타임아웃 설정 
          conn.setReadTimeout(3000); // 3초 
          
          // 요청 방식 구하기
          System.out.println("getRequestMethod():" + conn.getRequestMethod());
          // 응답 콘텐츠 유형 구하기
          System.out.println("getContentType():" + conn.getContentType());
          // 응답 코드 구하기
          System.out.println("getResponseCode():"    + conn.getResponseCode());
          // 응답 메시지 구하기
          System.out.println("getResponseMessage():" + conn.getResponseMessage());
          
          // 응답 헤더의 정보를 모두 출력
          for (Map.Entry<String, List<String>> header : conn.getHeaderFields().entrySet()) {
              for (String value : header.getValue()) {
                  System.out.println(header.getKey() + " : " + value);
              }
          }
          
          // 응답 내용(BODY) 구하기        
          try (InputStream in = conn.getInputStream();    
                  ByteArrayOutputStream out = new ByteArrayOutputStream()) {
              
              byte[] buf = new byte[1024 * 8];
              int length = 0;
              while ((length = in.read(buf)) != -1) {
                  out.write(buf, 0length);
              }
              
//              System.out.println(new String(out.toByteArray(), "UTF-8"));
              String sJson = new String(out.toByteArray(), "UTF-8");
              ObjectMapper mapper = new ObjectMapper();
                 
              map = mapper.readValue(sJson, Map.class);
              
          }
          
          // 접속 해제
          conn.disconnect();
    
          return map;
     }
cs
728x90