LoginSignup
0
2

More than 5 years have passed since last update.

APIのresponseをxml形式で受け取り、指定したタグのDOMを取得する

Last updated at Posted at 2017-02-20

API Requestを出し、ResponseをXMLで受け取り、指定のDOMを取得する。

意外と記載が少なかったので、ここにも記載しておきます。

APIを投げ、XML形式のResponseに記載があるsessionIDを使いたいということがありましたので、こんな投稿をしておきます。

String sendEncoding = "utf-8";
HttpURLConnection urlConn = null;
OutputStream out = null;
InputStream in = null;
URL url = new URL("APIのURL");
    urlConn = (HttpURLConnection) url.openConnection();
  // POSTでRequest
    urlConn.setRequestMethod("POST");
    urlConn.setDoOutput(true);
    urlConn.setRequestProperty("Content-Type", "text/xml;charset=" + sendEncoding);
    urlConn.connect();

    out = urlConn.getOutputStream();
    out.write(request.getBytes(sendEncoding));
    out.flush();

  // ここらでResponseを取得する。
  // これより下は
    in = urlConn.getInputStream();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(in);
    in.close();

   // Listでかえって来るのでいい感じにFor文を回してあげると
  // 欲しい値を取得できます。
    NodeList nodes = doc.getElementsByTagName("タグの名前");

xml形式のAPIを活用する際はぜひご活用ください。

0
2
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
0
2