0


I would like to do an HTTPRequest in Java and then get the data from the server (it's not a webpage the data come from a database).
I try this but the getData doesn't work.
Do you know how I can get the Data?

  public static void main(String args[]) throws Exception {
    URL url = new URL("http://ip-ad.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    System.out.println("Request method is " + httpCon.getData());
 }

Thanks

Glist
  • 79
  • 1
  • 4

2 Answers2

2

You can get the response body of the web request as an InputStream with:

httpCon.getInputStream();

From there it depends on what the format of the response data is. If it's XML then pass it to a library to parse XML. If you want to read it into a String see: Reading website's contents into string. Here's an example of writing it to a local file:

InputStream in = httpCon.getInputStream();
OutputStream out = new FileOutputStream("file.dat");
out = new BufferedOutputStream(out);
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
    out.write(buf, 0, len);
}
out.close();
Community
  • 1
  • 1
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • the response data is in byte. when I did the getInputStream() I have this answer : Request method is sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@83cc67. If I try the code that you give nothing is on the file – Glist May 10 '11 at 08:18
0

You can use http://jersey.java.net/ .

It's a simple lib for your needs.

k-deux
  • 493
  • 3
  • 13