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

前端 未结 9 1837
我在风中等你
我在风中等你 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:04

    i found the problem it's about ordering the code, if you are trying to add header and post parameters both, it's important to be careful about this

    HttpURLConnection connection = (HttpURLConnection) urlConnection;
    
    ////        Add Request Headers
    for (NameValuePair nvp :
             request[0].getHeaderParams()) {
         connection.setRequestProperty(nvp.getName(),nvp.getValue());
         }
    // done
    
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    ////         Add Post Parameters
    OutputStream outputStream = urlConnection.getOutputStream();
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
    List params = new ArrayList<>(request[0].getPostParams());
    bufferedWriter.write(getQuery(params));
    
    // done
    connection.setConnectTimeout(3000);
    connection.setReadTimeout(3000);
    bufferedWriter.flush();
    bufferedWriter.close();
    outputStream.flush();
    outputStream.close();
    connection.connect();
    

    in here, i have added header parameters then set setDoInput and setDoOutput then setRequestMethod and finally you can add POST parameters. i don't know what is wrong with setRequestMethod but i think its preparing the connection by opening it or something and that's why it throws exception

提交回复
热议问题