Monday, February 08, 2010

Java : Sending a HTTP OPTIONS command

The HTTP OPTIONS command is documented here.

I needed to do this programmatically and thought I would document the code.

 
import java.net.HttpURLConnection;
import java.net.URL;

...

try {
String type = "text/plain;charset=UTF-8";
URL url = new URL("http://xxx/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoOutput(true);
conn.setRequestMethod("OPTIONS");
conn.setRequestProperty("Content-Type", type);

System.out.println(String.format("HTTP %d: %s",
conn.getResponseCode(), conn.getResponseMessage()));

for(String header : conn.getHeaderFields().keySet() ){
System.out.println(String.format("%s : %s",
header, conn.getHeaderFields().get(header)));
}

String rMessage = conn.getResponseMessage();
System.out.println ("Response " + rMessage);

} catch (Exception e) {
e.printStackTrace();
}
}


Running this against Sun Java System Application Server 9.1 returns:

HTTP 200: OK
X-Powered-By : [Servlet/2.5]
Content-Length : [0]
Allow : [GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS]
null : [HTTP/1.1 200 OK]
Date : [Sun, 07 Feb 2010 19:11:57 GMT]
Server : [Sun Java System Application Server 9.1]
Content-Type : [text/html; charset=iso-8859-1]
Response OK


This sends something like "OPTIONS / HTTP/1.0". There is another version of the command that sends "OPTIONS * HTTP/1.0".

The "*" is actually part of the URI. However, "java.net.HttpURLConnection" has no facility which allows this. Some research suggests that this could be done by using "Apache Commons HttpClient".

Enjoy!

No comments: