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/