我正在尝试使用httpurlconnection发送帖子。一切看起来都很好,但它保持返回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 --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
它会返回我期待的访问令牌
1条答案
按热度按时间4zcjmb1e1#
键和值需要进行url编码(这是规范)。在您的示例中,将“test@”替换为“test%40”就足够了。对于经得起未来考验的解决方案,您应该对所有键和值进行编码(例如,使用URLCoder)