0

I'm trying to post data on a server using java HttpUrlConnection class. It seems that if I somehow read the response of the server, the post works fine, but if I don't, the information is never posted.

This kind of behaviour is not mentionned in the HttpUrlConnection doc and all examples I've seen of HttUrlConnection ask for a response from the server.

I want to know if I made a mistake in my code or if this is a normal behaviour of HttpUrlConnection, and if it's the case, can someone with a better understanding of how this class works explain to me why it's so?

Thanks a lot!

Here is the code, the commented line is the one that makes the POST either work or fail:

URL url=new URL("myUrl");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("Host", "myHost");
connection.setDoOutput(true);
os.write(staffToPost.getBytes("utf-8"));
os.flush();
os.close();
//System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());
settef
  • 11
  • 1
  • 3

2 Answers2

2

The URLCOnnection class needs a complete handshake for a POST to occur.This means, once you open a connection, you have to readback the response for the POST to actually take place.

UVM
  • 9,526
  • 5
  • 39
  • 63
  • Thanks, that explains things then. (I can't access the link for some reason though, it seems the topic got moved, I'll check that out...) – settef May 15 '12 at 05:23
  • Select the first link that is related to Oracle from the search results.Do not know why the links work straight away. – UVM May 15 '12 at 05:28
  • why -1 here? can anybody explain it? Thanks – UVM May 15 '12 at 05:39
  • :) Anyway I removed that link because it is not working when I access directly which I do not know the reason. – UVM May 15 '12 at 06:18
0

You can explicitly call URLConnection.connect() or get any information about the HTTP response such as HttpURLConnection.getResponseCode etc to trigger HTTP request.

You should go through this comprehensive post on How to use java.net.URLConnection to fire and handle HTTP requests for better understanding.

Community
  • 1
  • 1
Umer Hayat
  • 1,913
  • 4
  • 30
  • 56
  • I don't think `connect()` will commit the request. Getting the response code, message, or response `InputStream` will though. – erickson May 15 '12 at 04:56
  • Thanks, the link you sent was very useful. I tried using HttpURLConnection.connect() though and it didn't change anything. It seems that I have to explicitely access the response (with getResponseCode(), getInputStream()...) for the POST to work... I find this strange. – settef May 15 '12 at 05:12
  • OK, then I guess it's necessary to access the response to commit the POST. Thanks for your answers. – settef May 15 '12 at 05:16
  • @settef No worries, I am glad that it helped :) – Umer Hayat May 15 '12 at 05:18