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);

Advertisements

2 Comments

Filed under Java, web, webservice

2 responses to “Reading data from HttpURLConnection using Input Stream

  1. markan

    รับจ้างโพส รับจ้างโพสต์เว็บบอร์ด รับจ้างโพสข้อความ รับจ้างลงประกาศ โปรโหมดเว็บไซต์ 1000เว็บบอร์ด2000บาท สนใจสอบถามลายละเอียดที่เบอร์ 0873467837 24ชม

  2. Tons of videos we posted on the site. Love it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s