Created
July 4, 2013 09:49
-
-
Save tfnico/5926374 to your computer and use it in GitHub Desktop.
Sending a HTTP request with Java + Google Guava
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void sendMessage(String url, String params){ | |
final HttpURLConnection connection; | |
try { | |
URL requestUrl = new URL(url); | |
connection = (HttpURLConnection) requestUrl.openConnection(); | |
connection.setDoOutput(true); | |
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); | |
connection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length)); | |
connection.setRequestProperty("Content-Language", "en-US"); | |
sendRequest(params, connection); | |
String response = readResponse(connection); | |
System.out.println("Received response: "+response); | |
connection.disconnect(); | |
} catch (IOException e) { | |
throw Throwables.propagate(e); | |
} | |
} | |
private void sendRequest(String paramsToSend, final HttpURLConnection connection) throws IOException { | |
OutputSupplier<BufferedOutputStream> outputSupplier = new OutputSupplier<BufferedOutputStream>() { | |
@Override | |
public BufferedOutputStream getOutput() throws IOException { | |
return new BufferedOutputStream(connection.getOutputStream()); | |
} | |
}; | |
ByteStreams.write(paramsToSend.getBytes(), outputSupplier); | |
} | |
private String readResponse(final HttpURLConnection connection) throws IOException { | |
InputSupplier<InputStreamReader> supplier = CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { | |
@Override | |
public InputStream getInput() throws IOException { | |
return connection.getInputStream(); | |
} | |
}, Charset.defaultCharset()); | |
return CharStreams.toString(supplier); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://gist.github.com/tfnico/4c0fbe84bfbdffae0d7a for a more modern version using google-http-client.