Guava I / O Providers and URLConnection

I am trying to refactor (use Guava) a code that sends a POST request to a web service and reads a string response.

Currently my code looks like this:

    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);
    }

      

I would like to understand how to use Guava's InputSupplier and OutputSupplier correctly here to get rid of quite a lot of code. There are quite a few examples with files here, but I can't get a nice, concise version of the above code (I would like to see what happens with this experienced Guava user).

+3


source to share


1 answer


Much of the simplification you can get - like replacing strings out = conn.getOutputStream(); out.write(postData.getBytes()); out.close()

and having to close out

yourself,

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

      



This opens the output stream, writes the bytes, and correctly closes the output stream (as opposed to closeQuietly

).

+4


source







All Articles