Receive API response in xml format and get DOM of specified tag

Issue API Request, receive Response in XML, and get the specified DOM.

Surprisingly, there were few descriptions, so I will also describe them here.

I threw an API and wanted to use the sessionID described in the XML format Response, so I will post this.

String sendEncoding = "utf-8";
HttpURLConnection urlConn = null;
OutputStream out = null;
InputStream in = null;
URL url = new URL("API URL");
	urlConn = (HttpURLConnection) url.openConnection();
  //Request by POST
	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();

  //Get Response here.
  //Below this
	in = urlConn.getInputStream();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(in);
    in.close();

   //It will come back in the List, so if you turn the For statement nicely
  //You can get the value you want.
    NodeList nodes = doc.getElementsByTagName("Tag name");

Please use it when you use the API in xml format.

Recommended Posts

Receive API response in xml format and get DOM of specified tag
Format XML in Java
Create API to send and receive Json data in Spring
Get attributes and values from an XML file in Java
[Java] Get the dates of the past Monday and Sunday in order
Let's consider the meaning of "stream" and "collect" in Java's Stream API.