使用RestAssured发送POST请求遇500内部服务器错误,Postman请求正常
RestAssured调用POST接口返回500内部服务器错误的解决方案
我使用RestAssured向https://restful-booker.herokuapp.com/booking发送POST请求时收到500内部服务器错误,但用Postman调用同一接口能得到200成功响应。相关Java代码如下:
@Given("select POST request") public void select_POST_request() { RestAssured.baseURI="https://restful-booker.herokuapp.com/booking"; HashMap<String,String> head=new HashMap<String,String>(); head.put("Content-Type", "text/xml"); head.put("Accept", "*/*"); head.put("Connection", "keep-alive"); head.put("Accept-Encoding", "gzip, deflate, br"); Response resp = RestAssured .given() .log() .all() .headers(head) .body(body) .relaxedHTTPSValidation() .when() .post(); System.out.println(resp); System.out.println(resp.asPrettyString()); System.out.println(resp.getStatusCode()); Assert.assertEquals(resp.getStatusCode(), "200"); String body="<booking>\r\n"+ "<firstname>guru</firstname>\r\n" + "<lastname>swa</lastname>\r\n"+ "totalprice>12000</totalprice>\r\n" + "<depositpaid>5000</depositpaid>\r\n"+ "<bookingdates>\r\n"+ "<checkin>2023-09-25</checkin>\r\n"+ "checkout>2023-09-27</checkout>\r\n"+ "</bookingdates>\r\n"+ "additionalneeds>lunch</additionalneeds>\r\n"+"</booking>"; }
问题排查结果
- XML请求体语法错误:请求体中的
totalprice、checkout、additionalneeds标签缺少左尖括号<,导致XML格式完全无效,服务器无法解析请求内容,直接返回500错误。 - 断言类型不匹配:
Assert.assertEquals(resp.getStatusCode(), "200")中,getStatusCode()返回的是整数类型状态码,却与字符串"200"做比较,不仅会导致断言失败,也是代码中的明显逻辑错误。
修正后的代码
@Given("select POST request") public void select_POST_request() { RestAssured.baseURI="https://restful-booker.herokuapp.com/booking"; HashMap<String,String> head=new HashMap<String,String>(); head.put("Content-Type", "text/xml"); head.put("Accept", "*/*"); head.put("Connection", "keep-alive"); head.put("Accept-Encoding", "gzip, deflate, br"); // 修正XML标签的语法错误 String body="<booking>\r\n" + "<firstname>guru</firstname>\r\n" + "<lastname>swa</lastname>\r\n" + "<totalprice>12000</totalprice>\r\n" + "<depositpaid>5000</depositpaid>\r\n" + "<bookingdates>\r\n" + "<checkin>2023-09-25</checkin>\r\n" + "<checkout>2023-09-27</checkout>\r\n" + "</bookingdates>\r\n" + "<additionalneeds>lunch</additionalneeds>\r\n" + "</booking>"; Response resp = RestAssured .given() .log() .all() .headers(head) .body(body) .relaxedHTTPSValidation() .when() .post(); System.out.println(resp); System.out.println(resp.asPrettyString()); System.out.println(resp.getStatusCode()); // 修正断言的类型匹配问题,使用整数200进行比较 Assert.assertEquals(resp.getStatusCode(), 200); }
内容的提问来源于stack exchange,提问作者guru
相关产品推荐
相关产品推荐

