Mar 10

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: , , , ,

Oct 01

You need to build it manually from the ServletRequest.


StringBuilder sb = new StringBuilder("?");
for (Enumeration e = request.getParameterNames(); 
   e.hasMoreElements();)
{
      String param = (String) e.nextElement();
      sb.append(param)
        .append("=")
        .append(request.getParameter(param))
        .append("&");
}
String queryString = sb.toString().
   substring(0, sb.length() - 1); 

written by objects \\ tags: , ,

Sep 23

// Create query string

String queryString = "param1=" + 
   URLEncoder.encode(param1Value, "UTF-8");
queryString += "&param2=" +
   URLEncoder.encode(param2Value, "UTF-8");
    
// Make connection

URL url = new URL("http://www.objects.com.au/");
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
   urlConnection.getOutputStream());

// Write query string to request body

out.write(queryString);
out.flush();
    
// Read the response

BufferedReader in = new BufferedReader(
   new InputStreamReader(urlConnection.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
   System.out.println(line);
}
out.close();
in.close(); 

written by objects \\ tags: , , ,