Monday, 1 May 2017

Java - Reading the text content(xml/json) with out loop through 'InputStreamReader'

Reading the text content(xml/json) with out loop through 'InputStreamReader'.

Prerequisite:
Requires java 8 to execute below program

Sample Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;

public class Test8WsGet {

public static void main(String[] args) {
try {

URL url = new URL("http://thomas-bayer.com/sqlrest/CUSTOMER/2/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");

if (connection.getResponseCode() != 200) {
throw new RuntimeException("Failed with HTTP error code : " + connection.getResponseCode());
}

String responseXml;
System.out.println("Response xml from Server .... \n");

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
responseXml = bufferReader.lines().collect(Collectors.joining("\n"));

System.out.println(responseXml);

connection.disconnect();
} catch (Exception e) {
e.printStackTrace();

}
}
}
Troubleshooting :
If you are executing above program using maven(i.e. pom.xml) then add below maven-compiler-plugin
Reference: https://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>


Reading the text content(xml/json) from 'InputStreamReader' using 'while' loop.

Sample Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestWsGet {

public static void main(String[] args) {
try {

URL url = new URL("http://thomas-bayer.com/sqlrest/CUSTOMER/2/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");

if (connection.getResponseCode() != 200) {
throw new RuntimeException("Failed with HTTP error code : " + connection.getResponseCode());
}

String responseXml;
System.out.println("Response xml from Server .... \n");

BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
while ((responseXml = br.readLine()) != null) {
System.out.println(responseXml);
}

connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment