Skip to content

Instantly share code, notes, and snippets.

@samklr
Forked from tfnico/Something.java
Created July 4, 2013 11:43
Show Gist options
  • Select an option

  • Save samklr/5927007 to your computer and use it in GitHub Desktop.

Select an option

Save samklr/5927007 to your computer and use it in GitHub Desktop.
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