3

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 の経験豊富なユーザーがそれで何をするかを知りたいです)。

4

1 に答える 1

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.

于 2013-01-22T17:52:28.180 に答える