Please check this url from google: http://developer.android.com/reference/java/net/HttpURLConnection.html
It is good to use the openConnection() method before setting the headers. Here are the steps from the documentation:
- Get a new HttpURLC connection by calling URL.openConnection () and passing the result to HttpURLConnection.
- Prepare a request. The main property of a request is its URI. Claim headers can also include metadata, such as credentials, preferred content types, and session cookies.
- Optionally load the request body. Instances must be configured using
setDoOutput(true) if they include the request body. Pass the data by writing to the stream returned by getOutputStream() . - Read the answer. Response headers typically include metadata, such as the type and length of response body content, modified dates, and session cookies. The response body can be read from the stream returned by
getInputStream() . If the response does not have a body, this method returns an empty stream. - Disconnect. When the response body is read, the
HttpURLConnection should be closed by calling disconnect() . Disabling releases the resources held by the connection, so they can be closed or reused.
However, if the problem persists, you can either try to debug your code or check your own connection.connected flag to find out where it becomes true; I had a similar problem after calling getContentType() method.
Otherwise, you can simply switch to the HttpClient API:
HttpClient httpclient = new DefaultHttpClient();
source share