본문 바로가기

Java Programming/Java

사업자번호 유효성검사_xml 전문 통신 및 xml 파싱(국세청 api 호출)

package test1;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class TestApi1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
String test = ""; 
test = soapDataTransfer();
System.out.println("test : "+test);
}

public static String soapDataTransfer() {
 
    try {
        URL url;
        url = new URL("https://teht.hometax.go.kr/wqAction.do?actionId=ATTABZAA001R08&screenId=UTEABAAA13&popupYn=false&realScreenId=");

 

        //XML문 구성 : txprDscmNo 태그안에 사업자번호 입력
        String xmldata1 = 

"<map id='ATTABZAA001R08'><pubcUserNo/><mobYn>N</mobYn><inqrTrgtClCd>1<inqrTrgtClCd><txprDscmNo>111234567890</txprDscmNo><dongCode>05</dongCode><psbSearch>Y</psbSearch><map id='userReqInfoVO'/></map>";

        
        //SSL 인증을 무조건 true로 만드는 소스 코드
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { 
              public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
                    return null; 

              } 

              public void checkClientTrusted(X509Certificate[] certs, String authType) { 
              } 

              public void checkServerTrusted(X509Certificate[] certs, String authType) { 
              } 
        } };
        SSLContext sc = SSLContext.getInstance("SSL"); 

        sc.init(null, trustAllCerts, new java.security.SecureRandom());  
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

 

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
               public boolean verify(String string,SSLSession ssls) {
                      return true;
               }
        }); 

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();

        //연결 시간과 header 설정
        conn.setConnectTimeout(3000);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "text/xml");
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(xmldata4);
        wr.flush();
        InputStreamReader in = new InputStreamReader(conn.getInputStream(),"utf-8");
        BufferedReader br = new BufferedReader(in);
        String strLine;
        String returnString = "";
        /*
         * 보낸 XML에 대한 응답을 받아옴
         */
        while ((strLine = br.readLine()) != null){
            returnString = returnString.concat(strLine);
        }
        in.close();
        wr.close();
/////////////////////////////////////////////////////////////////xml 전문 통신 끝

   
        /*
         * 보낸 XML에 대한 응답을 출력.
         */
        System.out.println(returnString);
        
        // XML Document 객체 생성 (XML 파싱)
        InputSource is = new InputSource(new StringReader(returnString));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(is);

        // 인터넷 상의 XML 문서는 요렇게 생성하면 편리함.
        //Document document =                   DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("http://www.example.com/test.xml");

        // xpath 생성
        XPath xpath = XPathFactory.newInstance().newXPath();

        // NodeList 가져오기 : row 아래에 있는 모든 col1 을 선택
        NodeList cols = (NodeList)xpath.evaluate("//map/trtCntn", document, XPathConstants.NODESET);
        for( int idx=0; idx<cols.getLength(); idx++ ){
               System.out.println(cols.item(idx).getTextContent());
        }

} catch (Exception e) {
        e.printStackTrace();
}        

    return "soapDataTransfer";
}