我正在尝试重构(利用Guava)一些代码,这些代码向Web服务发送POST请求并读取对字符串的回复。
目前我的代码如下:
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有经验的用户会做些什么)。
答案 0 :(得分:4)
您可以获得的大部分简化 - 例如它 - 将替换行out = conn.getOutputStream(); out.write(postData.getBytes()); out.close()
,以及需要自己关闭out
new ByteSink() {
public OutputStream openStream() throws IOException {
return conn.getOutputStream();
}
}.write(postData.getBytes());
打开输出流,写入字节,并正确关闭输出流(而不是closeQuietly
)。