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);
byte[] response = out.toByteArray();

written by objects \\ tags: , , , ,

One Ping to “How to write GET response to byte array?”

  1. How to access ftp server using URL class? | web development helpdesk Says:

    […] The URL can then be used to open a connection to the URL and read the contents […]

2 Responses to “How to write GET response to byte array?”

  1. -=JFK=- Says:

    I have been looking everywhere for some Java code that would allow me to get an image file from a URL and then convert it into a byte[] to store in SQL Server 2000 database. I have seen many examples but they got image from URL and store in java.awt.Image object. This didn’t help because I was having to do all sorts of work to then turn that into a byte[]. Also, I was running into Serialization errors like: “java.io.NotSerializableException: java.awt.image.BufferedImage”

    I was able to use this VERY simple example to pull a JPG from Google (after having them resize the image using param passing) and then post to our SQL Server 2000 database for use on our site.

    You da (wo)man!
    I have spent serveral hours this mornign trying to tackle this prob. 🙂


  2. objects Says:

    No worries, glad it helped you

Leave a Reply

You must be logged in to post a comment.