给出 java.lang.IllegalStateException 的 setRequestProperty 方法:建立连接后无法设置方法

Har*_*der 5 java android httpconnection

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");
Run Code Online (Sandbox Code Playgroud)

嗨,我在调用方法时遇到java.lang.IllegalStateException: Cannot set method after connection is made错误setRequestProperty,但是当我在连接之前调用此方法时,我得到了NullPointerException因为con为空。我能做些什么来解决这个问题?

Dav*_*ton 0

不要使用 URL 的便捷方法,使用HttpURLConnection或其他库。

  • 抱歉,我没有安静地让你使用 HttpURLConnection。你的意思是我不应该使用 url.openConnection (2认同)