Skip to content

Instantly share code, notes, and snippets.

@tfnico
Created July 4, 2013 09:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tfnico/5926374 to your computer and use it in GitHub Desktop.
Save tfnico/5926374 to your computer and use it in GitHub Desktop.
Sending a HTTP request with Java + Google Guava
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);
}
@tfnico
Copy link
Author

tfnico commented Jul 1, 2015

See https://gist.github.com/tfnico/4c0fbe84bfbdffae0d7a for a more modern version using google-http-client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment