I am trying to refactor (to take advantage of Guava) some code that sends a POST request to a web service and reads the reply to a string.
Currently my code looks like that:
HttpURLConnection conn = null;
OutputStream out = null;
try {
// Build the POST data (a JSON object with the WS params)
JSONObject wsArgs = new JSONObject();
wsArgs.put("param1", "value1");
wsArgs.put("param2", "value2");
String postData = wsArgs.toString();
// Setup a URL connection
URL address = new URL(Constants.WS_URL);
conn = (HttpURLConnection) address.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setConnectTimeout(Constants.DEFAULT_HTTP_TIMEOUT);
// Send the request
out = conn.getOutputStream();
out.write(postData.getBytes());
out.close();
// Get the response
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
Log.e("", "Error - HTTP response code: " + responseCode);
return Boolean.FALSE;
} else {
// Read conn.getInputStream() here
}
} catch (JSONException e) {
Log.e("", "SendGcmId - Failed to build the WebService arguments", e);
return Boolean.FALSE;
} catch (IOException e) {
Log.e("", "SendGcmId - Failed to call the WebService", e);
return Boolean.FALSE;
} finally {
if (conn != null) conn.disconnect();
// Any guava equivalent here too?
IOUtils.closeQuietly(out);
}
I would like to understand how to use properly Guava’s InputSupplier and OutputSupplier here to get rid of quite a bunch of code. There are quite a few examples out here with files but I can’t get a nice concise version of the above code (would like to see what a Guava experienced user would do with that).
The majority of the simplification you’ll be able to get — such as it is — would be to replace the lines
out = conn.getOutputStream(); out.write(postData.getBytes()); out.close(), and the need to closeoutyourself, withThat opens the output stream, writes the bytes, and closes the output stream properly (as opposed to
closeQuietly).