setRequestProperty方法的给java.lang.IllegalStateException:不能设置方法是由连接后方法、是由、setRequestProperty、java

2023-09-13 01:59:55 作者:带着虚伪滚

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");

你好我收到 java.lang.IllegalStateException:不能设置方法是由连接后错误时,调用setRequestProperty 方法是所谓的,但是当我连接之前调用此方法,我得到 NullPointerException异常,因为 CON 为空。我能做些什么来解决这个?

Hi I am getting java.lang.IllegalStateException: Cannot set method after connection is made error when setRequestProperty method is called ,but when I call this method before connection I get NullPointerException because con is null. What can I do to solve this?

推荐答案

这可能工作:

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