try { //enter statements that can cause exceptions }

URL url = new URL(“http://exampleurl. com/”); HttpURLConnection client = (HttpURLConnection) url. openConnection(); For best practice, establish the URL and HttpURLConnection objects outside of the try block to make it easier to catch exceptions. URL url = new URL(“http://exampleurl. com/”); HttpURLConnection client = null; try { client = (HttpURLConnection) url. openConnection(); }

The setRequestProperty() function is used as the Accept-Encoding request header to disable automatic decompression. client. setRequestMethod(“POST”); client. setRequestProperty(“Key”,”Value”); client. setDoOutput(true);

OutputStream outputPost = new BufferedOutputStream(client. getOutputStream()); writeStream(outputPost); outputPost. flush(); outputPost. close(); For performance reasons, it’s a good idea to let the server know how large in bytes the content will be. The best method is setFixedLengthStreamingMode(int) when the body length is known,[4] X Research source whereas setChunkedStreamingMode(int) is used if it’s length is not known. [5] X Research source Not using either of the previous methods causes the HttpURLConnection object to buffer the complete body in memory before being transmitted. client. setFixedLengthStreamingMode(outputPost. getBytes(). length); client. setChunkedStreamingMode(0);

catch(MalformedURLException error) { //Handles an incorrectly entered URL } catch(SocketTimeoutException error) { //Handles URL access timeout. } catch (IOException error) { //Handles input and output errors }

finally { if(client != null) // Make sure the connection is not null. client. disconnect(); }