Give Java Setrequestproperty method of lang.illegalstateexception: method cannot be set after connection is established

HttpURLConnection con = null;
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");

Hi, I got Java Lang.IllegalStateException: after calling the setRequestProperty method, the method error after the connection cannot be set, but when I call this method before connecting, I get NullPointerException, because con is null.. What can I do to solve this problem?

Solution

From Google: http://developer.android.com/reference/java/net/HttpURLConnection.html View this URL

You can use the openconnection () method before setting the title Here are the steps in the document:

>By calling URL Openconnection() and convert the result to httpurlconnection to get a new httpurlconnection. > Prepare the request The main attribute of the request is its URI The request header can also include metadata such as credentials, preferred content types, and session cookies. > (optional) upload request body If the instance contains the request body, it must be configured using setdoutput (true) Transfer data by writing the stream returned by getoutputstream(). > Read the reply The response header usually includes metadata, such as the content type and length of the response body, the modification date, and the session cookie The response body can be read from the stream returned by getinputstream() If the response has no body, the method returns an empty stream. > Disconnect Once the response body has been read, httpurlconnection should be closed by calling disconnect () Disconnecting frees resources owned by the connection so that they can be closed or reused

However, if the problem persists, you can try debugging the code and checking the connection Connected private flag to see where it becomes true; After calling the getcontenttype () method, I encountered a similar problem

Otherwise, you can 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);
....
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>