3

我正在尝试重构(利用 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();
        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 经验的用户会如何处理)。

4

1 回答 1

4

您将能够获得的大部分简化 - 例如 - 将替换 lines out = conn.getOutputStream(); out.write(postData.getBytes()); out.close(),并且需要关闭out自己,

new ByteSink() {
  public OutputStream openStream() throws IOException {
    return conn.getOutputStream();
  }
}.write(postData.getBytes());

这会打开输出流,写入字节,并正确关闭输出流(而不是closeQuietly)。

于 2013-01-22T17:52:28.180 回答