2

Sorry, I'm quite new to Java.

I've stumbled across HttpGet and HttpPost which seem to be perfect for my needs, but a little long winded. I have written a rather bad wrapper class, but does anyone know of where to get a better one?

Ideally, I'd be able to do

String response = fetchContent("http://url/", postdata);

where postdata is optional.

Thanks!

Tim Green
  • 2,028
  • 1
  • 17
  • 19
  • Just to add, I'm not 'expecting' to be able to do it in one line. It's just an example - I realise Java is probably more precise and I will require try's and catch's for everything to work properly. – Tim Green May 13 '10 at 19:30
  • "Cannot instantiate the type HttpClient" - that's what I get when I try to use HttpClient for "HttpClient client = new HttpClient();" – Tim Green May 13 '10 at 19:41

2 Answers2

5

HttpClient sounds like what you want. You certainly can't do stuff like the above in one line, but it's a fully-fledged HTTP library that wraps up Get/Post requests (and the rest).

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • If you end up doing anything real with it, you probably will require authentication/ssl (which HttpClient supports). – Justin May 13 '10 at 19:36
2

I would consider using the HttpClient library. From their documentation, you can generate a POST like this:

PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
  new NameValuePair("user", "joe"),
  new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

There are a number of advanced options for configuring the client should you eventually required those.

Eric Hauser
  • 5,551
  • 3
  • 26
  • 29