Sep 16

// Create query string

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

URL url = new URL(""+queryString);
URLConnection urlConnection = url.openConnection();
// Read the response

BufferedReader in = new BufferedReader(
   new InputStreamReader(urlConnection.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)

written by objects \\ tags: , , , ,

Jun 11

Many developers use the toURL() method of the File class to convert a File to a URL. This method however does not handle correctly escaping characters that are illegal in URL’s (such as spaces) and has been deprecated.

To convert a File to a URL you should instead first use the toURI() method to convert the file path to a URI. The URI class has a toURL() method that can then be used to convert the URI to a URL.

File file = new File(path);
URI uri = file.toURI();
URL url = uri.toURL();

// or alternatively in one line

URL url = file.toURI().toURL();

written by objects \\ tags: , , ,

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

// now write file to connections output stream

written by objects \\ tags: , , , ,