HttpUrlConnection 错误请求

HttpUrlConnection Bad Request

我正在尝试使用 HttpUrlConnection 发送 POST。一切似乎都很好,但它保持 returns 400,就好像参数没有在 DataOutputStream 中发送,或者无论如何以格式错误的方式发送。

public String doDBAuth(String dbURL, String dbUser, String dbPassword) throws IOException {
    HttpURLConnection connection = null;

    String res = null;

    try {
        BufferedReader reader;
        StringBuffer buffer;

        URL url = new URL(dbURL + "/auth");
        connection = (HttpURLConnection) url.openConnection();          
        String urlParameters  = "username=actn-admin&password=Test@&cliend_id=admin-cli&grant_type=password";
        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8 );
        int postDataLength = postData.length;



        connection.setRequestMethod("POST");
        connection.setReadTimeout(40000);
        connection.setConnectTimeout(40000);
        connection.setDoOutput(true);   
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");     
        connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        connection.setDoInput(true);


        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.writeBytes(urlParameters);
            wr.flush();
        }


        int responseCode = connection.getResponseCode();

        int status = connection.getResponseCode();
        InputStream inputStream;
        if (status == HttpURLConnection.HTTP_OK) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));
        buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        res = buffer.toString();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }   
    return res;
}  

这是返回的内容:

{"error":"unauthorized_client","error_description":"INVALID_CREDENTIALS: Invalid client credentials"}

这很奇怪,因为这个 curl 工作正常:

curl --location --request POST '<URL>/auth' \
> --header 'Content-Type: application/x-www-form-urlencoded' \
> --data-urlencode 'username=actn-admin' \
> --data-urlencode 'password=Test@' \
> --data-urlencode 'client_id=admin-cli' \
> --data-urlencode 'grant_type=password' -k

它 returns 我期待的访问令牌

键和值需要 URL 编码(here 的规范)。 在您的示例中,将“Test@”替换为“Test%40”就足够了。对于面向未来的解决方案,您应该对所有键和值进行编码(例如使用 URLEncoder