Java: HTTP PUT with HttpURLConnection

Paul Tarjan picture Paul Tarjan · Jan 20, 2010 · Viewed 7k times · Source

How do you do do an HTTP PUT? The class I'm using seems to think it is doing a PUT but the endpoint is treating it as if I did a GET. Am I doing anything wrong?

URL url = new URL("https://...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(xmlString);
writer.close();

System.out.println(conn.getRequestMethod());
String response = readInputStream(conn.getInputStream());
System.out.println(response);

Which is printing:

PUT
<same content as doing a GET>

I'd rather not include another library if this one could work...

Answer

Jon Skeet picture Jon Skeet · Jan 20, 2010

There's one easy way to find out: run Wireshark and see what's actually happening on the network. I've found that to be the most reliable way of diagnosing this sort of issue - your client could have bugs, the library could have bugs, the server could have bugs, but Wireshark will show you what's really happening.

EDIT: Okay, for HTTPS it's a little trickier. You can use Fiddler if you're running on Windows, which is a proxy - it can cope with HTTPS if you can persuade your client code to accept its certificate, but that's a little more intrusive... putting a proxy in the way clearly changes what the traffic looks like.

It would be better if you could talk to a debug version of the server over HTTP instead. Is that feasible in your case, or is the server completely outside your control?