我正在尝试使用POST RESTful服务。当我在邮递员上尝试时,我得到了成功的答复。但是,当我用以下代码在Java上尝试时,我的响应代码是400。在邮递员中,我粘贴了相同的输入内容,但替换了转义字符。
try {
URL url = new URL("https://localhost/PasswordVault/api/Accounts");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\", \"detail\":{\"ver\":\"2020\",\"productionDate\":\"2020\"}}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
System.out.println("Exception:- " + e);
}
一些想法:
"post data".getBytes(StandardCharsets.UTF_8)
connection.getErrorStream()
)例如
// handle error code
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
// use getErrorStream for non OK statuses (https://stackoverflow.com/questions/613307/read-error-response-body-in-java)
String errorMessage = "HTTP response code: " + responseCode
+ (responseMessage == null || responseMessage.trim().length() == 0 ? "" : " " + responseMessage);
InputStream errorStream = connection.getErrorStream();
if(errorStream != null) {
String errorString = streamToString(connection.getErrorStream());
if(errorString.length() > MAX_MSG_LENGTH) {
errorString = errorString.substring(0, Math.min(MAX_MSG_LENGTH, errorString.length())) + "...";
}
errorMessage += ", HTTP response data: " + errorString;
}
throw new RuntimeException(errorMessage);
}
// handle OK code
// ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句