// 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
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: convert, file, URI, url
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