无法POST,HttpURLConnection默认为GET

Unable to POST, HttpURLConnection defaults to GET

我正在尝试 POST 到某个端点,但 URL 不允许使用 GET 方法。使用 HTTPURLConnection 时,我将请求方法设置为 post 并将 doOutput 设置为 true。

但是由于某些原因,当我在 InputStream 上设置断点时(由于缺少文件而失败),请求方法为 GET,并且 doOutput 为 false(只有 doInput 为 true)。这会导致 404, 方法不允许 未找到 ,表示方法 [get] 没有匹配的处理程序。为什么它会忽略我的设置并继续进行,就好像我什么都没输入一样?

String result = null;
    try {
        HttpURLConnection connection = (HttpURLConnection)new URL(baseUrl  + getTokenPath).openConnection();

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((clientid + ":" + secret).getBytes()));
        connection.setDoOutput(true);


        DataOutputStream wr = new DataOutputStream (
                connection.getOutputStream ());

        wr.writeBytes ("grant_type=client_credentials");
        wr.flush ();
        wr.close ();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        result = response.toString();
        rd.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

在您从 InputStream 读取所有数据之前不要关闭 DataOutputStream

wr.close ();

关闭流会导致您断开连接。 Flush 足以发送 POST 请求。

wr.flush ();