setRequestProperty throwing java.lang.IllegalStateException: Cannot set request property after connection is made

前端 未结 9 1811
我在风中等你
我在风中等你 2020-12-17 17:35

I am getting java.lang.IllegalStateException:

java.lang.IllegalStateException: Cannot set request property after connection is made error w

相关标签:
9条回答
  • 2020-12-17 18:15

    To avoid the error:

    java.lang.IllegalStateException: Cannot set request property after connection is made

    We have to check the connection response before access the request header fields :

    URL url = new URL("https://49.205.102.182:7070/obsplatform/api/v1/mediadevices/545b801ce37e69cc");
         urlConnection = (HttpsURLConnection) url
        .openConnection();
    
    //Check connection
    if(urlConnection.getResponseCode() == 200/*Successful*/) {      
       urlConnection.setRequestProperty("Content-Type","application/json");
      ...
      ...    
     }
    
    0 讨论(0)
  • 2020-12-17 18:16

    The obvious thing is to think that you need to add properties before calling open on the URL. this however is not the case. i have seen many samples of settings being set AFTER url has been open (as counter intuitive as that is).

    the problem in my case is that i had conn.getResponseCode() added in my watch list. removed that and all good.

    ... tricky.

    0 讨论(0)
  • 2020-12-17 18:23

    please check below code

    HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
    httpcon.setDoOutput(true);
    httpcon.setRequestProperty("Content-Type", "application/json");
    httpcon.setRequestProperty("Accept", "application/json");
    httpcon.setRequestMethod("POST");
    httpcon.connect();
    
    0 讨论(0)
提交回复
热议问题