I want to compose a HTTP request message in java and then want to send it to a HTTP WebServer. I also want the document content of the page recieved which I would have recieved if I sent the same HTTP request from a webpage.
You can use java.net.HttpUrlConnection.
You can find sample code snippets at Java Almanac. Browse for java.net.
From Sun's java tutorial
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html
In particular, getHeaderField, getHeaderFieldKey, and getContent
I know others will recommend Apache's http-client, but it adds complexity (i.e., more things that can go wrong) that is rarely warranted. For a simple task, java.net.URL
will do.
URL url = new URL("http://www.y.com/url");
InputStream is = url.openStream();
try {
/* Now read the retrieved document from the stream. */
...
} finally {
is.close();
}
Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.
Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.
I think I do not have proper privilege to comment on posts here. But links in this response does not work the correct example URLs are Apache HttpClient and Apache HttpCore
I guess mods can update it.