오랜만에 자바 포스팅하나를 작성하러 돌아왔습니다.


이번에 소개드릴것은 구글의 GSON 입니다.


GSON은 자바 라이브러리중 하나인데, 자바 오브젝트를 쉽게 JSON으로 변환시켜주는 아주 간단하고 심플한 라이브러리 입니다.


주로 Simple-JSON이나, JACKSON등 많은 JSON관련 라이브러리가 있는데요.


이 중에서 제가 사용해본 자바 라이브러리에선 가장 간편하고 편하지 않나 싶습니다.


먼저 GitHub 주소를 첨부하도록 하겠습니다.


GitHub Google Gson 바로가기 


Gson is a Java library that can be used to convert Java Objects into their JSON representation.

(Gson은 Java 객체를 JSON 표현으로 변환하는 데 사용할 수 있는 Java 라이브러리 입니다.)


라고 안내하고있습니다.


Gson은 자바객체를 -> JSON으로, JSON을 -> 자바객체로도 쉽게 표현 및 변환이 가능합니다.


자 그럼, Gson샘플 코드에 대해 알아보도록 하겠습니다.



GSON을 알아보자!


Gson은 jar파일로 바로 프로젝트에 연결시켜서 사용 할 수도있지만 Maven 프로젝트나 Gradle 프로젝트에서도 바로 연결하여 사용 할 수 있습니다.


해당 안내는 위 GitHub에 있지만 아래 첨부하겠습니다.


Gradle:

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}

Maven:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>

Jar:
Gson jar 다운로드 Maven Central. 


* eclipse-jee-2018-09-win32-x86_64

* gson 2.8.6




저는, Jar파일을 받아 프로젝트에 Add시켰습니다.

그럼 간단한 샘플을 시작해보도록 하겠습니다.



1. Map -> JSON, JSON -> Map 


1
2
3
4
5
6
7
8
9
10
11
12
13
Gson gsonObj = new Gson();
    
Map<StringString> inputMap = new HashMap<StringString>();
inputMap.put("name""makesomething");
inputMap.put("blog""https://web-inf.tistory.com");
        
// MAP -> JSON 예제
String jsonStr = gsonObj.toJson(inputMap);
System.out.println("MAP -> JSON 예제 : " + jsonStr);
        
// MAP -> JSON 예제
Map map = gsonObj.fromJson(jsonStr, Map.class);
System.out.println("JSON -> MAP 예제 : " + map.toString());
cs


Map에서 JSON은 Gson객체 선언후 toJson, JSON에서 Map은 객체 선언 후 fromJson입니다.

단 fromJson은 변환 할 타입(Class)을 확실이 잡아주어야 합니다.


List등, CustomClass도 JSON으로 변환이 가능하고, 자바 객체라면 모두 변환이 가능 합니다.



2. JsonObject 만들기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// JsonObject 생성
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name""makesomething");
jsonObject.addProperty("blog""http://web-inf.tistory.com");
jsonObject.addProperty("boolean"true);
jsonObject.addProperty("int"12345);
        
System.out.println("JsonObject 생성 : " + jsonObject.toString() + "\n");
 
// String 리턴
System.out.println("JsonObject name(String) : " + jsonObject.get("name").getAsString());
System.out.println("JsonObject blog(String) : " + jsonObject.get("blog").getAsString());
 
// boolean 리턴
System.out.println("JsonObject boolean(boolean) : " + jsonObject.get("boolean").getAsBoolean());
 
// int 리턴
System.out.println("JsonObject int(int) : " + jsonObject.get("int").getAsInt());

cs


Gson에서 JsonObject 만드는 방법 입니다.

간단하게, JsonObject객체를 선언한 후에, Map처럼 addProperty로 데이터를 넣어주면 됩니다.

하지만 addProperty는 자료형 타입별로 넣어 줄 수 있고, 다시 Object에서 자료를 꺼낼때도 타입별로 리턴 받을 수 있습니다.

(sys.out.println의 마지막 .get부분을 보시면 타입별로 리턴받는것을 확인 하실 수 있습니다.)



3. JsonArray 만들기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// JsonObject 생성
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name""makesomething");
jsonObject.addProperty("blog""http://web-inf.tistory.com");
jsonObject.addProperty("boolean"true);
jsonObject.addProperty("int"12345);
                
System.out.println("JsonObject 생성 : " + jsonObject.toString() + "\n");
        
// JsonArray 생성
JsonArray jsonArray = new JsonArray();
jsonArray.add(jsonObject);
        
System.out.println(jsonArray.toString());
    
// JsonArray 0번 index에있는 jsonObject의 name을 string으로 리턴
System.out.println(jsonArray.get(0).getAsJsonObject().get("name").getAsString());
cs


JsonObject를 응용하여 JsonArray를 생성해보았습니다.

JsonArray에 만들었던 JsonObject(JsonElement)를 넣고, JsonObject안에 있는 name데이터를 String으로 리턴받는 예제 입니다.


JsonArray에서 ADD시 사용할수있는 메소드 입니다.

자료형 별로 구분되어있고 JsonElement는 JSON요소 모두를 의미합니다. (JsonObject, JsonArray등)



3. Gson Parse Pretty


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// JsonObject 생성
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name""makesomething");
jsonObject.addProperty("blog""http://web-inf.tistory.com");
jsonObject.addProperty("boolean"true);
jsonObject.addProperty("int"12345);
                
System.out.println("JsonObject 생성 : " + jsonObject.toString() + "\n");
        
// Parse Pretty
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(jsonObject);
        
System.out.println(jsonOutput);
cs


마지막으로, GsonBuilder옵션입니다.

Builder옵션은 더 많은 종류와 설정 메소드들이 존재하지만 그 중에서 Json을 이쁘게 출력을 해주는 Pretty 옵션 예제 입니다.

Gson 객체를 선언 후 setPrettyPrinting으로 변환해주면 결과 값이 개행이 잘되어 나타납니다.




결과값입니다. 예쁘게 개행이 된 것을 확인 할 수 있습니다.



이렇게 Gson은 명확히, 자료형으로 데이터를 넣을수있고 리턴받을수있게 구현이 되어있습니다.

속도도 빠르며, 코드가 더욱더 깔끔해지며 JSON을 사용하기가 편리합니다.


다만 단점을 꼽자면, 코드가 조금 길어지는 느낌도 있습니다.


하지만, 개발자 입장에서 봤을때 한눈에 알아보기가 쉬운 장점이 있습니다. (저만 그럴수도있어요..)


저는 Gson을 만난 후 다른 Json라이브러리는 특수한 상황이 아니라면 Gson만 사용하네요.ㅎㅎ


이상으로, Gson 포스팅을 마치도록 하겠습니다.

감사합니다.


반응형


JAVA언어에서 어쩌면 가장 많이 활용하며 사용하는 Map입니다.

Map은 기본적으로 Key와 Value를 묶어 한쌍 으로 저장 합니다.

그리고 많은 양의 데이터를 빠르게 검색 할 수있는 성능의 장점이 있습니다.


JAVA의 Map도 종류가 많은데요. (Hash, Tree, Linked)

그중 HashMap과 LinkedHashMap의 차이점에 대해 알아 보려합니다.


1. HashMap, LinkedHashMap 사용법 


1
HashMap hashMap = new HashMap<>();
cs


HashMap 객채 생성을 합니다. 

HashMap은 제네릭타입을 지정하여 생성 할 수도 있습니다.

LinkedHashMap도 동일합니다.

(LinkedHashMap linkedHashMap = new LinkedHashMap<>();)


1
2
3
4
hashMap.get("key"); // 키쌍 매핑된 데이터를 가져옵니다. return value
hashMap.isEmpty(); // 맵안에 데이터가 있는지 여부를 확인 합니다. return true/false
hashMap.containsKey("key"); // 맵안에 해당키가 있는지 여부를 확인합니다. return true/false 
hashMap.size(); // 맵의 크기를 확인 합니다. return int
cs


기본적으로 많이 사용하는 HashMap 메소드들 입니다.

LinkedHashMap도 동일합니다.


get() : 매핑한 키의 value값을 가져옵니다.

isEmpty() : 맵안 데이터 존재 여부를 확인 합니다. 비어있다면 true를 리턴합니다.

containsKey() : 맵안에 해당 키가 존재하는지 확인합니다. 있다면 true를 리턴합니다.

size() : 맵의 크기를 확인합니다. 키쌍매핑이 1개라면 int 1 리턴합니다.






2. HashMap VS LinkedHashMap  차이점&성능


먼저, HashMap과 LinkedHashMap의 큰차이점은 키쌍을 매핑했을때 순서 입니다.


HashMap은 순서대로 저장이 되지 않습니다.


1
2
3
4
5
6
HashMap hashMap = new HashMap<>();
hashMap.put("apple""apple");
hashMap.put("banana""banana");
hashMap.put("tomato""tomato");
            
System.out.println(hashMap.toString());
cs




반면, LinkedHashMap은 순서대로 저장 됩니다.


1
2
3
4
5
6
LinkedHashMap linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("apple""apple");
linkedHashMap.put("banana""banana");
linkedHashMap.put("tomato""tomato");
                
System.out.println(linkedHashMap.toString());

cs




그렇다면.. 둘의 성능차이가 있을까? 라는 의문을 품게 되었습니다.

왜냐하면, LinkedHashMap은 정렬이 되어 저장되기 때문입니다.


결론을 말씀드리면 LinkedHashMap이 약간 더 우세하다라는 의견이 더욱 많았습니다.

맵을 Create하는 시간이 조금더 걸리는반면, Access속도와 Iterate속도가 조금 더  빠르게 작용하였습니다.

(물론, 제가 퍼포먼스 테스트한것은 아닙니다.)


하지만, HashMap과 LinkedHashMap의 최종 속도 차이는 큰차이가 없다는 결론 입니다.

(아래 참고 링크를 확인해주세요.)

* 출처 StackOverflow : https://stackoverflow.com/questions/12998568/hashmap-vs-linkedhashmap-performance-in-iteration-over-values



간단하게, 성능차이가 궁금하여 검색해보던 중 포스팅 정리하게 되었습니다.

감사합니다.


반응형


오늘은 FCM콘솔로 푸시를 보내지 않고, 자바 스프링MVC 웹서버(WAS)를 이용하여 이전에 구현했던 안드로이드 어플리케이션으로 푸시를 보내보겠습니다.


먼저 FCM 푸시를 수신받을 어플리케이션을 제작 및 FCM 콘솔에 프로젝트를 생성을 하셔야합니다.

(사전 준비가 되지 않으신분은 아래에 이전에 작성한 포스팅 자료의 링크를 참조해주시면 되겠습니다.)


FCM 프로젝트 생성 및 FCM 수신 어플리케이션 제작

https://web-inf.tistory.com/21


이번 과정에서는 스프링MVC 프로젝트를 만드는과정은 간단한 과정이기 때문에 생략하고 진행하도록 하겠습니다.


1. 시작하기 


먼저 이전 앱 서버로 푸시를 보내는 가이드 문서가 업데이트되어 HTTP v1 API로 변경이 되었습니다.

해당 문서는 FCM 프로젝트에서 비밀 KEY파일을 받아 Access Token을 발급 받은 뒤, Access Token과 함께 안드로이드의 해당 Device Token으로 푸시 요청을 보내는 과정입니다.


구글 FCM HTTP v1 API 가이드 문서

 https://firebase.google.com/docs/cloud-messaging/send-message?hl=ko


먼저 Access Token을 발급과정을 위해 key파일을 생성해보겠습니다.



FCM 콘솔에 접속을 합니다.

그리고 저번에 생성해뒀던 FCM TEST 프로젝트가 보이네요.

자신이 사용하는 FCM 프로젝트를 클릭해서 접속해주세요.

콘솔 링크 : https://console.firebase.google.com/u/0/project/_/settings/serviceaccounts/adminsdk?hl=ko



프로젝트에 접근한뒤, 설정에 서비스 계정 항목을 선택해서 들어가주세요.



오늘은 JAVA를 이용하여 작업을 진행하기 때문에, 자바를 선택하신뒤 비공개 키 생성 버튼을 눌러주세요.



한번더 경고창이 나오며 묻게 됩니다.

키 생성을 눌러 비밀키 JSON파일을 다운로드 받아주세요.

다운로드 하신 파일은 잘보관해주세요. 이후 작업에 사용됩니다.



2. SpringMVC 프로젝트에 API 구현하기




먼저 스프링MVC Maven, JAVA1.8 프로젝트와 톰캣을 준비하였습니다.

구현하는 용도에따라 다른분들은 구성이 달라질것이라 생각하여 프로젝트 생성 및 과정은 생략하였습니다.


또한 구글에서 제공하는 API에서는 자바환경에 Gradle 가이드만 제공되고 있어 Maven으로 동작시켜보았습니다.

세부적인 DB연결과 프로퍼티 저장등은 샘플환경만보시고 따로 작업해주시면 될 것 같습니다.





1. 준비과정 - 디바이스 토큰(Device Token)

먼저 이전에 만들어놓은 어플리케이션에서 디바이스 토큰을 가져 옵니다.

위 스크린샷에 MainActivity를 실행했을때 로그로 DeviceToken을 획득하게 설정해준후 에뮬레이터로 가져왔습니다.

(디바이스 토큰은 가끔 변경이 되므로 DB에 저장을 해두던가 별도의 방법으로 refresh받아 작업하시면될것같습니다.)





로그에 디바이스 토큰을 가져온 스크린샷 입니다.

디바이스토큰을 어디에 기록해두시면 됩니다.





2. 준비과정 - Firebase admin SDK 비밀키

먼저 사전에 생성해놓은 비밀키를 프로젝트 내에 복사해주세요.

저는 webapp > resources > google > json 경로에 복사해두었습니다.

(따로 키를 DB에 보관하시거나 저장하는 작업은 별도로 진행하시면 될 것 같습니다.)



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
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/com.google.api-client/google-api-client -->
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>1.26.0</version>
        </dependency>
                        
        <!-- https://mvnrepository.com/artifact/com.google.oauth-client/google-oauth-client -->
        <dependency>
            <groupId>com.google.oauth-client</groupId>
            <artifactId>google-oauth-client</artifactId>
            <version>1.26.0</version>
        </dependency>
                
        <!-- https://mvnrepository.com/artifact/com.google.http-client/google-http-client -->
        <dependency>
            <groupId>com.google.http-client</groupId>
            <artifactId>google-http-client</artifactId>
            <version>1.26.0</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/com.google.http-client/google-http-client-jackson2 -->
        <dependency>
            <groupId>com.google.http-client</groupId>
            <artifactId>google-http-client-jackson2</artifactId>
            <version>1.26.0</version>
        </dependency>  
        
        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.0.1-jre</version>
        </dependency>
 
cs


3. 준비과정 - Maven FCM전용 라이브러리 업데이트


프로젝트의 pom에 해당 dependecy를 붙여놓고 라이브러리를 다운받아주세요.

구글 가이드에서는 api-client라이브러리만 다운받으면 진행이 된다고 적혀있지만, 사실상 위에 기재된 라이브러리가 모두 필요하였습니다.

추가로 Spring의 RestTemplate을 사용하였으며, API로 파라미터를 넘길때는 JSON을 사용하였습니다.

(많은 삽질이 있었습니다.)




GOOGLE SEND API를 보시면 이제, 액세스 키 발급조건과, 디바이스토큰은 획득하였으며 POST방식으로 푸시를 보내주기만 하면됩니다.

(위 API 문서 링크에 있는 자료 입니다.)


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
@RequestMapping(value="/fcmTest", method=RequestMethod.GET, produces="text/plain;charset=UTF-8")
    public void fcmTest() throws Exception {
        try {    
            
            String path = "C:/** .. **/webapp/resources/google/{fcm-test-*******************************.json}";           
            String MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
            String[] SCOPES = { MESSAGING_SCOPE };
            
            GoogleCredential googleCredential = GoogleCredential
                                .fromStream(new FileInputStream(path))
                                .createScoped(Arrays.asList(SCOPES));
            googleCredential.refreshToken();
                                
            HttpHeaders headers = new HttpHeaders();
            headers.add("content-type" , MediaType.APPLICATION_JSON_VALUE);
            headers.add("Authorization""Bearer " + googleCredential.getAccessToken());
            
            JSONObject notification = new JSONObject();
            notification.put("body""TEST");
            notification.put("title""TEST");
            
            JSONObject message = new JSONObject();
            message.put("token""fa_qIyte8d4:APA91bHOGnZulT059PyK3z_sb1dIkDXTiZUIuRksmS7TdK6XgXAS5kopeGIwUfyhad3X3iXMNknCUOZaF6_mgoj1ohG10CanRyJ_EW1d3xN2E-1DPiLdbMK4pdOgdhB1ztZClqB-25rC");
            message.put("notification", notification);
            
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("message", message);
            
            HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(jsonParams, headers);
            RestTemplate rt = new RestTemplate();            
            
            ResponseEntity<String> res = rt.exchange("https://fcm.googleapis.com/v1/projects/{프로젝트명}/messages:send"
                    , HttpMethod.POST
                    , httpEntity
                    , String.class);
        
            if (res.getStatusCode() != HttpStatus.OK) {
                log.debug("FCM-Exception");
                log.debug(res.getStatusCode().toString());
                log.debug(res.getHeaders().toString());
                log.debug(res.getBody().toString());
                
            } else {
                log.debug(res.getStatusCode().toString());
                log.debug(res.getHeaders().toString());
                log.debug(res.getBody().toLowerCase());
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
cs


먼저 풀소스 입니다.

테스트용으로 컨트롤러 단에 바로 호출하여 동작하도록 작성하였습니다.

'{ }' 부분은 자신의 조건에 맞춰 기입하셔야합니다.


구글 액세스키를 발급받은뒤 RestTemplate을 통하여 POST로 푸시를 발송하는 과정 입니다.

이제 중요포인트만 따로 뽑아서 설명을 드리고 마치겠습니다.




1. AccessKey 발급


먼저 AccessKey를 발급하기위해서는, 비밀키 경로를 InputStream으로 읽을수 있게 요구합니다.

절대경로로 작성되어야 하며, 차후에 프로퍼티에 기록 또는 DB 기록작업을 작업하시면 될 것 같습니다.





2. 푸시 내용 및 디바이스토큰으로 전송


발급된 액세스토큰을 HTTP헤더에 넣습니다. (빨간색 박스)

푸시내용을 JSON Object으로 API파라미터 조건에 맞게 담습니다. (초록색 박스)

앱에서 가져온 디바이스 토큰을 JSON Object로 API파라미터 조건에 맞게 담습니다. (노란색 박스)

마지막으로 요청할 주소를 넣습니다.

주의사항으로 자신의 프로젝트ID를 기입하여야 합니다. (파란색박스)

(프로젝트ID는 프로젝트 콘솔 -> 설정 -> 일반 에서 확인할수 있습니다.)


코드 작성을 마치셨으면 발송 후 로그를 확인 합니다.


요청을 통하여 '200' 으로 정상 요청이 되었다는것을 확인할수있습니다.



에뮬레이터 역시나 정상도착하여 아까 기입한 'TEST' 라는 푸시가 날라온걸 확인 할 수 있습니다.



이상으로 Spring MVC Maven 프로젝트를 통한 FCM 푸시 보내기를 마치겠습니다.



반응형


평상시 Restful 방식으로 Json 혹은 Text를 주고 받던중에 또 다른 웹서비스 방식중인 Soap 방식을 자바로 요청응답을 주고 받아야 하는일이 생겼습니다.

우선 Soap방식의 경우 XML을 요청 하고 응답을 받는데요.


오늘은 SOAPMessage를 이용한 XML을 요청 -> XML을 응답을 자바(Java)로 받는 과정을 포스팅을 하겠습니다.


SOAP (Simple Object Access Protocol) 이란?


SOAP은 HTTP, HTTPS, SMTP등을 사용하여 XML 기반의 메시지를 컴퓨터 네트워크 상에서 교환하는 형태의 프로토콜로써 웹 서비스(Web Service)의 기본적인 메시지 전송 수단이며 XML-RPC와 WDDX에서 envelope/header/body로 이루어진 구조와 전송(transport)과 상호 중립성(interaction neutrality)의 개념을 도입하였다. 

-> 쉽게말해 HTTP, HTTPS등 통신프로토콜 위에서 XML 메시지를 요청응답 받는것 입니다.



자바로 SOAP 요청/응답 하기 


먼저 부분 부분소스 분석을 한 뒤 하단에 풀소스를 첨부하겠습니다.

(급하신분들은 미리 맨하단 샘플소스를 참조해주시면되겠습니다.)


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
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        
factory.setNamespaceAware(true);             
DocumentBuilder parser = factory.newDocumentBuilder();
 
//request SOAP message DOMSource create
String sendMessage = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<root> " +
        "     <body>" +
        "         <record>" +
        "               ... " +
        "           ... " +
        "           ... " +
        "        </record>" + 
        "    <body>" +
        "</root> "
        
StringReader reader = new StringReader(sendMessage);
InputSource is = new InputSource(reader);
Document document = parser.parse(is);
DOMSource requestSource = new DOMSource(document);
 
//SOAPMessage create
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage requestSoapMessage = messageFactory.createMessage(); 
SOAPPart requestSoapPart = requestSoapMessage.getSOAPPart(); 
requestSoapPart.setContent(requestSource);
cs


세세한 설명보단 큰흐름만 집고 넘어가도록하겠습니다.

먼저 보낼(요청할) SOAP XML을 String으로 담고 MessageFactory, SOAPMessage등으로 요청할 XML로 파싱합니다.



1
2
3
4
5
6
//SOAPConnection create instance
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection connection = scf.createConnection();
 
//SOAP SEND MESSAGE
SOAPMessage responseSoapMessage = connection.call(requestSoapMessage, "요청보낼 URL");
cs

요청할 SOAP XML을 생성한후, SOAPMessage를 요청할 연결준비를 합니다.

새로운 커넥션을 맺고 요청보낼 URL을 입력합니다.



1
2
3
4
5
6
7
8
9
10
11
12
ByteArrayOutputStream out = new ByteArrayOutputStream();
responseSoapMessage.writeTo(out);
                
SOAPBody soapBody = responseSoapMessage.getSOAPBody();  
Iterator i = soapBody.getChildElements();  
Node node = (Node) i.next();
          
JSONParser jsonParser = new JSONParser();
JSONObject soapResult = (JSONObject) jsonParser.parse(node.getChildNodes().item(0).getChildNodes().item(0).getNodeValue());
            
log.debug(soapResult.toString());
 
cs


*응답 XML안에 JSON값이 있을경우*

요청에 성공하였다면 responseSoapMessage 응답값을 OutputStream에 담고 만약 응답 SOAP XML내부에 JSON형식의 String이 있다면,

내부 Body노드를 찾아 JSON으로 파싱후 결과값을 출력 하면 됩니다.



1
2
3
4
5
6
ByteArrayOutputStream out = new ByteArrayOutputStream();
responseSoapMessage.writeTo(out);
 
String soapResult = new String(out.toByteArray(), "UTF-8");
 
log.debug(soapResult);
cs

*응답 XML을 찍어내고 싶은경우*

만약, JSON String이 아니라면 단순 응답값을 String으로 찍어낸후 확인하는 방법이 있습니다.


SAMPLE 소스 


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
60
61
62
63
64
65
66
67
68
69
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
 
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; 

try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        
        factory.setNamespaceAware(true);             
        DocumentBuilder parser = factory.newDocumentBuilder();
 
        //request SOAP message DOMSource create
        String sendMessage = 
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<root> " +
            "     <body>" +
            "         <record>" +
            "               ... " +
            "           ... " +
            "           ... " +
            "        </record>" + 
            "    <body>" +
            "</root> "
            
        StringReader reader = new StringReader(sendMessage);
        InputSource is = new InputSource(reader);
        Document document = parser.parse(is);
        DOMSource requestSource = new DOMSource(document);
 
        //SOAPMessage create
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage requestSoapMessage = messageFactory.createMessage(); 
        SOAPPart requestSoapPart = requestSoapMessage.getSOAPPart(); 
        requestSoapPart.setContent(requestSource);
 
        //SOAPConnection create instance
        SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = scf.createConnection();
 
        //SOAP SEND MESSAGE
        SOAPMessage responseSoapMessage = connection.call(requestSoapMessage, "요청보낼 URL");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        responseSoapMessage.writeTo(out);
        //String soapResult = new String(out.toByteArray(), "UTF-8");
 
        SOAPBody soapBody = responseSoapMessage.getSOAPBody();  
 
        Iterator i = soapBody.getChildElements();  
        Node node = (Node) i.next();
          
        JSONParser jsonParser = new JSONParser();
        JSONObject soapResult = (JSONObject) jsonParser.parse(node.getChildNodes().item(0).getChildNodes().item(0).getNodeValue());
            
        log.debug(soapResult.toString());
 
catch (Exception e) {
    e.printStackTrace();
}       
cs

단순 import한 라이브러리, 클래스와 try/catch문 안의 핵심 소스만 첨부하였습니다.

샘플로만으로도 충분히 구현 할 수 있을 것입니다.


반응형

+ Recent posts