07. POST 방식 호출

2015. 8. 6. 16:54JAVA/Webservice(REST)

포스트 방식 호출을 위한 클라이언트 생성

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class CallREST {
 public static void main(String[] args) throws Exception {
  String xml = "<?xml version='1.0'?>                           "+
                "<x:addCustomer xmlns:x='http://cxf.gnnet.co.kr/'>        "+
                "<customer>                                         "+
                "    <id>1234</id>                                  "+
                "    <name>HaksooKim</name>              "+
                "    <address>Ilsan</address>               "+
                "</customer>                                       "+
                "</x:addCustomer>                               ";
 
  URL url = new URL("http://localhost:8080/REST/services/CXFServicePort/addCustomer");
 
  HttpURLConnection conn = (HttpURLConnection)url.openConnection();
     conn.setDoOutput(true);
  conn.setRequestMethod("POST");
  // Header 영역에 쓰기
  conn.addRequestProperty("Content-Type", "text/xml");
     // BODY 영역에 쓰기
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
     wr.write(xml);
  wr.flush();
    
     // 리턴된 결과 읽기
     String inputLine = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((inputLine = in.readLine()) != null) {
         System.out.println(inputLine);
        }
        in.close();
  wr.close();
 }
}




앞서 봤던 SOAP 방식의 Webservice를 포스트로 호출 했을때와 다른점은 서버로 전달되는 XML의 형식이다.
SOAP 방식에서는 SOAP 프로토콜에 맞게 SOAP:ENV와 SOAP:HEADER, SOAP:BODY등을 명확히 명시해줘야 하지만 RESTful 방식에서는 내부적으로는 SOAP 프로토코을 사용 할지라도 실제 사용자 입장에서는 단순 XML만 넘겨주고 받으면 되는 것이다.

* 소스에서 <x:addCustomer xmlns:x='http://cxf.gnnet.co.kr/'> wrapper element로써 우리가 beans.xml에 다음과 같이 wrapped속성에 true라고 했기 때문에 customer element 바깥에 addCustomer라는 wrapper element로 감싸줘야 한다.




만약 wrapped속성을 false로 지정하면 앞의 [RESTful Step6] 단계에서 GET방식으로 id 파라미터를 넘기는 부분에서 다음과 같은 오류가 발생할 것이다.

org.apache.cxf.interceptor.Fault: A URI parameter cannot be mapped to a simple type in unwrapped mode

'JAVA > Webservice(REST)' 카테고리의 다른 글

[RESTFul] ResponseEntity 제너릭 타입 사용 타입처리 방법???  (5) 2018.01.25
06. 서비스 호출  (0) 2015.08.06
05. beans.xml과 web.xml  (0) 2015.08.06
04. 프로젝트의 시작  (0) 2015.08.06
03. Eclipse 환경설정  (0) 2015.08.06