tags:

views:

43

answers:

1

How can I do the equivalent of the Ruby snippet below using Java?

require 'net/http'
res = Net::HTTP.get_response(URI.parse("http://somewhere.com/isalive")).body
+1  A: 
URL url = new URL("http://somewhere.com/isalive");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();

and then, if you want, you can transform the InputStream to String using IOUtils.toString(inputStream) from apache commons-lang, or something like this.

Update: the above classes should be imported first, with a statement ontop of the class definition:

import java.net.URL;
import java.net.URLConnection;
.. and so on
Bozho
The place I need to use the Java doesn't look like it's got the IOUtils library. How can I read the stream into a string without it?
sipwiz
Turns out I could use IOUtils I just needed to prefix it with org.apache.commons.io.
sipwiz
@sipwiz: or import it, just like the other classes. Note that the code above will use the platform default encoding to convert the input stream to a String, which can corrupt the data. To avoid that, you should use the HttpURLConnection class and look at the content-type response header. Or use the Apache HTTP client library which can do this automatically.
Michael Borgwardt