Java Reference
In-Depth Information
return stringToXMLDocument(getHttpUrl(URL_API_ROOT + resource.name()));
}
public Document getResourceItem(Resource resource, int itemId) {
return stringToXMLDocument(
getHttpUrl(URL_API_ROOT + resource.name() + "/" + itemId));
}
public String getHttpUrl(String url) {
HttpURLConnection connection = null;
try {
URL u = new URL(url);
connection = (HttpURLConnection) u.openConnection();
// We will be making GET requests only to this service
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
// We got a non 200 (OK) status code: error or server is down
System.err.println("Server returned status code: " + responseCode);
return null;
}
// Fetch the response from the server
StringBuilder stringBuilder = new StringBuilder();
// getInputStream is data coming back from the server
// getOutputStream is meant for sending data to the server
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
String s;
while ((s = reader.readLine()) != null) {
stringBuilder.append(s + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
return stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
return null;
}
static public Document stringToXMLDocument(String xmlText) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(
new StringReader(xmlText)));
return document;
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
Search WWH ::




Custom Search