Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: HTTP PUT with HttpURLConnection

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...

like image 582
Paul Tarjan Avatar asked Jan 20 '10 07:01

Paul Tarjan


People also ask

How will you send a delete request using HTTP URL connection?

there is a simple way for delete and put request, you can simply do it by adding a " _method " parameter to your post request and write " PUT " or " DELETE " for its value!


1 Answers

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?

like image 123
Jon Skeet Avatar answered Oct 18 '22 00:10

Jon Skeet