java - Guava 输入/输出供应商和 URLConnection

标签 java android inputstream guava urlconnection

我正在尝试重构(以利用 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 经验的用户会用它做什么)。

最佳答案

您将能够获得的大部分简化——实际上是——替换行 out = conn.getOutputStream(); out.write(postData.getBytes()); out.close(),并且需要自己关闭out,用

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

打开输出流,写入字节,并正确关闭输出流(与 closeQuietly 相反)。

关于java - Guava 输入/输出供应商和 URLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14464486/

相关文章:

android - 在 Android AudioTrack 中使用缓冲区

java - 如何避免类型转换?

java inputStream一次只读取一个标签

java - FileInputStream.read() 什么时候阻塞?

java - 导入 android.content.Context 后无法解析上下文;还

java - 正则表达式删除特殊字符(拉丁语1)

java - 为什么传递的数组不能使用lambda函数

android - 带有包含两个 TextView 和 CheckBox 的 MyAdapter 的 ListView

java - 如何链接到包但仅根据运行时包的存在/可用性选择性地执行操作?

java - 是否有用于 Java 输入流的简单 “tee” 过滤器?