POST 편안한 서비스를 사용하려고합니다. Postman에서 시도하면 성공적인 응답을 얻습니다. 그러나 아래 코드를 사용하여 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] 삭제
몇 마디 만하겠습니다