Feb 18

To send a HTTP GET request using Java can be done with the URL class. The openStream() method will send the GET request and return an input stream that can be used to read the HTTP response.

Wrapping the stream in a BufferedInputStream can be done to improve the I/O performance.

The ByteArrayOutputStream makes it easy to write the contents of the response to a byte array as shown in the following example.

URL url = new URL("http://www.objects.com.au/services/sherpa.html");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
   out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();

written by objects \\ tags: , , , ,