0

I want to use HttpURLConnection to connect to my webservice, POST an XML and get a result. I am using the following code:

URL url = new URL(urlString);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

Problem is, when I call the setRequestProperty method, it fails with an IllegalStateException saying I am "already connected". Apparently, openConnection in fact opens the connection to the URL (in my debugger, I can see the connected boolean set to true). According to the URL documentation of Oracle though, it shouldn't. The Android docs are unclear about it.

How do I prevent openConnection to connect, so I can set extra properties?

Update it looks like the connection is in some pool and doesn't get disconnected, not even after calling connection.disconnect(), or even killing the server.

I do not think this is a duplicate of this question as it gives no real answer. Also, the documentation seems to be unclear.

Community
  • 1
  • 1
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • possible duplicate of [setResponseCode method giving java.lang.IllegalStateException: Cannot set method after connection is made](http://stackoverflow.com/questions/7726195/setresponsecode-method-giving-java-lang-illegalstateexception-cannot-set-method) and few others ... – Selvin Jun 23 '15 at 09:50
  • 3
    @Selvin yes. That is more than three years old, and has no accepted answer. And the answers it does have, do not fix it. – Bart Friederichs Jun 23 '15 at 09:51
  • then you should add bounty ... not repeat the question ... you wana newer? [here](http://stackoverflow.com/questions/30147312/java-lang-illegalstateexception-cannot-set-request-property-after-connection-i) – Selvin Jun 23 '15 at 09:59
  • @Selvin that one is older – Bart Friederichs Jun 23 '15 at 10:01
  • heheh ok :) just use setRequestProperty("connection", "close") (and maybe keep-alive false) in prev use of any connection in your app – Selvin Jun 23 '15 at 10:02
  • @Selvin I'd love to, but no properties can be set anymore ... – Bart Friederichs Jun 23 '15 at 10:04
  • so it is a first connection in the app? – Selvin Jun 23 '15 at 10:05
  • It is correct to setRequestProperty() after openConnection(). However, before setting any meta data, make sure to set the desired http request method. In your case: connection.setRequestMethod(HttpConnection.POST); – Andrei Mărcuţ Jun 23 '15 at 10:05
  • @Markus, `setDoOutput` takes care of that – Bart Friederichs Jun 23 '15 at 10:07
  • and the API version of device is .... – Selvin Jun 23 '15 at 10:18

1 Answers1

-1

openConnection() does not connect, and the code you have posted does not behave as yu have described. What opens the TCP connection is any of the following:

  • getInputStream()
  • getErrorStream()
  • getResponseCode()

Ergo you must have called one of those before trying to set a request property.

user207421
  • 305,947
  • 44
  • 307
  • 483