Web サービスに POST 要求を送信し、文字列への応答を読み取るコードを (Guava を利用するために) リファクタリングしようとしています。
現在、私のコードは次のようになっています。
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);
}
ここで Guava の InputSupplier と OutputSupplier を適切に使用して、大量のコードを取り除く方法を理解したいと思います。ここにはファイルを含むかなりの数の例がありますが、上記のコードの簡潔なバージョンを得ることができません (Guava の経験豊富なユーザーがそれで何をするかを知りたいです)。