// Create query string
String queryString = "param1=" +
URLEncoder.encode(param1Value, "UTF-8");
queryString += "¶m2=" +
URLEncoder.encode(param2Value, "UTF-8");
// Make connection
URL url = new URL("http://www.obiweb.com.au"+queryString);
URLConnection urlConnection = url.openConnection();
// Read the response
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
written by objects
\\ tags: GET, query string, request, url, URLConnection
When using URLConnection (HttpURLConnection actually) to send a large POST you can often get a OutOfMemoryError, for example when POSTing a large file.
Reason for this is that by default HttpURLConnection buffers the entire POST to enable it to set the content length for the request.
If you already know the content length in advance (for example when sending a file) you can use streaming mode.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setFixedLengthStreamingMode(file.length());
// now write file to connections output stream
written by objects
\\ tags: HttpURLConnection, OutOfMemoryError, post, url, URLConnection
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: ByteArrayOutputStream, GET, http, url, URLConnection