Tag Archives: Input Stream

Reading data from HttpURLConnection using Input Stream

When you are developoing applications (desktop or mobile) you often have to deal with web based services that you need to interact over HTTP(s). You would use “HttpURLConnection” class to connect to a remote web service and invoke calls using the “URL” aggreed upon.

example :

URL url = new URL(“https://api.linkedin.com/v1/people/~”);
HttpURLConnection request = (HttpURLConnection) url.openConnection();

Once you havre the HttpURLConnection object, you can invoke “getInputStream()” method to access the response returned by the remote web application/URL.

example :

InputStream in = (InputStream) request.getInputStream();

In order to read the data in the InputStream object returned, you can use the following code.

example :

final char[] buffer = new char[0x10000];
StringBuilder out = new StringBuilder();
Reader r = new InputStreamReader(in, “UTF-8”);
int read;
do {
read = r.read(buffer, 0, buffer.length);
if (read>0) {
out.append(buffer, 0, read);
}
}
while (read>=0);

2 Comments

Filed under Java, web, webservice