SetRequestProperty method providing java.lang.IllegalStateException: cannot set method after connection

HttpURLConnection con = null; Response response = new Response(); String TAG = "HttpConHandler"; try{ /* * IMPORTANT: * User SHOULD provide URL Encoded Parms */ Log.p(TAG, "URL="+ urlStr); String q=httpHeaders.get("Authorization"); URL url = new URL(urlStr); con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("Authorization", q); con.setRequestProperty("GData-Version", "3.0"); 

Hey. I get java.lang.IllegalStateException: Cannot set method after connection is made when calling setRequestProperty method, but when I call this method before connecting, I get NullPointerException because con is null. What can I do to solve this problem?

+4
source share
3 answers

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(); // Prepare a request object HttpGet httpget = new HttpGet(url); // Execute the request HttpResponse response; try { response = httpclient.execute(httpget); .... 
+1
source

Do not use the URL convenience method, use HttpURLConnection or another library.

0
source

This may work:

 URL url = new URL(urlStr); con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestProperty("Authorization", q); con.setRequestProperty("GData-Version", "3.0"); 
0
source

All Articles