Java 番石榴输入/输出供应商和URLConnection
我试图重构(利用Guava)一些代码,将POST请求发送到web服务并读取对字符串的回复 目前,我的代码如下所示:Java 番石榴输入/输出供应商和URLConnection,java,android,inputstream,guava,urlconnection,Java,Android,Inputstream,Guava,Urlconnection,我试图重构(利用Guava)一些代码,将POST请求发送到web服务并读取对字符串的回复 目前,我的代码如下所示: HttpURLConnection conn = null; OutputStream out = null; try { // Build the POST data (a JSON object with the WS params) JSONObject wsArgs = new JSONObject();
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来删除大量代码。这里有很多关于文件的示例,但我无法获得上述代码的简洁版本(希望了解有番石榴经验的用户会如何处理这些代码)。您可以得到的大部分简化(比如)是替换行
out=conn.getOutputStream();out.write(postData.getBytes());out.close()
,并且需要用
new ByteSink() {
public OutputStream openStream() throws IOException {
return conn.getOutputStream();
}
}.write(postData.getBytes());
打开输出流、写入字节并正确关闭输出流(与
closequilly
相反)。番石榴似乎不会显著简化此操作。另外,番石榴也不推荐。谢谢你的回答。阅读回答的内容如何?您将如何读取字符串的整个响应?可能类似于CharStreams.toString(CharStreams.newReaderSupplier(newInputSupplier(){…},Charsets.which_CHARSET_是合适的))代码>我用一个更完整的例子创建了一个要点:@LouisWasserman我注意到在最近版本的Guava中,它不再编译了,供应商也不推荐使用。想要更新吗?下面是一个使用google http java客户端和Guava的示例: