LoginSignup
5
7

More than 5 years have passed since last update.

JAVAでGET通信してXMLを読み込む方法のメモ

Last updated at Posted at 2016-07-12

JAVAでXMLがあるURLからGET通信して、ノードの文字列を取得する方法のメモになります。

XMLUtil.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class XMLUtil {

    /*
     *GET通信してXMLを取得するメソッド
    */
    public static InputStream getXMLFromHttp() throws  Exception{
        HttpURLConnection connection = null;
        try{
            // XMLの取得元URL設定
            URL url = new URL("http://www.xxx.xxx.xxx");

            // コネクションをオープン
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // レスポンスが来た場合は処理続行
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // InputStreamを返す
                return connection.getInputStream();
            }else{
                Exception e = new IOException();
                throw e;
            }

        }catch(Exception e){
            throw e;
        }finally{
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /*
     *XMLからコンテンツを取得するメソッド
    */
    public static String getXMLContents(InputStream is) throws  Exception{
        try{
            // GET通信で取得したXMLを読み込み
            Document document= DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

            // タグのnameからコンテンツのノードを取得
            Element rootElement=document.getDocumentElement();
            NodeList nodeList = rootElement.getElementsByTagName("文字列の値を取得するタグ名");

            //最初の1つめのXMLのノードの値を取得
            Element elem = (Element)nodeList.item(0);
            return elem.getFirstChild().getNodeValue();

        }catch(Exception e){
            throw e;
        }   
    }    
}

参考URL

【3. XML文書を読む2 (2) | TECHSCORE(テックスコア)】
http://www.techscore.com/tech/Java/JavaSE/DOM/3-2/

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7