2
我想通過HttpUrlConnection
發佈一個json
請求(請注意,我只需要將數據推送到服務器,響應將被忽略)。我已經通過了幾個例子,但仍然無法實現它,沒有數據被添加到服務器。HttpUrlConnection請求不工作,沒有讀取響應
這裏是我的代碼:
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStream stream = connection.getOutputStream();
stream.write(requestJSON.toString().getBytes());
stream.flush();
stream.close();
更新
我注意到代碼的工作,當我嘗試stream.close()
後讀取響應,如:
connection.getResponseMessage()
那是手段有必要閱讀響應以完成請求?
之前的'stream.close()''添加connection.connect(); ' – user155542
使用如下示例'OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream,「utf-8」)); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close();' – BNK