Wrapper class for HttpGet / Post in Java?
Sorry I'm pretty new to Java.
I came across HttpGet and HttpPost which seem to be perfect for my needs, but a little long. I wrote a pretty bad wrapper class, but does anyone know where to get it better?
Ideally I could do
String response = fetchContent("http://url/", postdata);
where postdata is optional.
Thanks!
+2
a source to share
2 answers
HttpClient sounds like what you want. You certainly can't do things like above on one line, but this is a complete HTTP library that completes Get / Post requests (and the rest).
+5
a source to share
I would consider using the HttpClient library . From the documentation, you can create 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 several additional options for customizing the client if you ultimately need them.
+2
a source to share