Note that there are some explanatory texts on larger screens.

plurals
  1. POGuava Input/Output Suppliers and URLConnection
    text
    copied!<p>I am trying to refactor (to take advantage of Guava) some code that sends a POST request to a web service and reads the reply to a string.</p> <p>Currently my code looks like that:</p> <pre><code> 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); } </code></pre> <p>I would like to understand how to use properly Guava's InputSupplier and OutputSupplier here to get rid of quite a bunch of code. There are quite a few examples out here with files but I can't get a nice concise version of the above code (would like to see what a Guava experienced user would do with that).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload