无法在 Android 应用程序的 HttpUrlConnection 中设置 headers

Unable to set headers in HttpsUrlConnection in AndroidApp

我正在从 URL class 创建 HttpsUrlConnection。我正在使用 setRequestPropety 方法在连接中添加一些 header 字段,如以下代码所示。

URL url = new URL(address);
HttpURLsConnection connection = (HttpsURLConnection) url.openConnection();
connection.disconnect();
connection.setRequestProperty("Accept", "application/json");

我遇到异常,java.lang.IllegalStateException:在执行 setRequestMethod 建立连接后无法设置请求 属性。我什至尝试断开连接,如上面的代码所示。

提前致谢。

注意:我也尝试用 addRequestProperty 替换 setRequestProperty 但在例外情况下没有区别。

注意:堆栈跟踪如下

10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime: Process: com.MYCOM.po, PID: 29470
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at android.os.AsyncTask.done(AsyncTask.java:300)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:  Caused by: java.lang.IllegalStateException: Cannot set request property after connection is made
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpURLConnectionImpl.setRequestProperty(HttpURLConnectionImpl.java:496)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.setRequestProperty(DelegatingHttpsURLConnection.java:258)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at com.android.okhttp.internal.http.HttpsURLConnectionImpl.setRequestProperty(HttpsURLConnectionImpl.java:25)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at com.MYCOM.po.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:386)
10-27 13:53:40.352 29470-30420/com.MYCOM.po E/AndroidRuntime:     at com.MYCOM.po.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:364)

注意:我使用的是 Studio 提供的 LoginActivity 模板;将应用程序连接到 RESTful 网络服务。

doInBackground方法如下

    @Override
    protected Boolean doInBackground(Void... params) {

        try {

            URL url = new URL(address);// Stored as a field in AsyncTask

            HttpURLConnection connection;
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("REST-API-Key", "HEXKEY");
            connection.setRequestProperty("Accept", "application/json");
            StringBuilder paramBuilder = new StringBuilder();
            paramBuilder.append("PARAM1=");
            paramBuilder.append("VALUE1");
            paramBuilder.append("&");
            paramBuilder.append("PARAM2=VALUE2");
            paramBuilder.append("&");
            paramBuilder.append("PARAM3=");
            paramBuilder.append("VALUE3");
            connection.setDoOutput(true);
            OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
            outputWriter.write(paramBuilder.toString());
            outputWriter.flush();
            if(connection == null) {
                Thread.sleep(2000);
                return false;
            }
            BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            if(responseReader == null){
                throw new IOException("Null Response");
            }
            StringBuilder sb = new StringBuilder();
            String line;
            while((line = responseReader.readLine())!=null){
                sb.append(line+"\n");
            }
            String resp = sb.toString();
            connection.disconnect();


        } catch (InterruptedException|IOException e) {
            return false;
        }


        // TODO: register the new account here.
        return true;
    }

请从您的代码中删除 connection.disconnect()

典型的使用模式是:

HttpUrlConnection ucon = (HttpUrlConnection) url.openConnection();
ucon.setRequestProperty("name", "value");
...
InputStream is = null; 
try {
  is = ucon.getInputStream();
  // read inputstream. ideally wrapping it in a BufferedReader.
} finally {
  if (is != null) is.close();
}

在断开连接之前,您至少应该设置 header。

URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept", "application/json");

try {
     InputStream in = new BufferedInputStream(connection.getInputStream());
     readStream(in);
finally {
     connection.disconnect();
}

奇怪,但我删除了所有断点,除了最后一个检查结果并且它起作用了。我猜是断点造成的延迟;是问题所在。我仍然不明白为什么即使 connection.connect() 没有被执行它也会连接。 解决方案是不中断网络操作。