我用Java构造了这个JSON请求。我将使用我的URL和此请求找到一个休息模板。
{
"searchRequest":{
"header":{
"agency":"1111",
"agent":"2222";
"from":"0";
"size":"15"
},
"requestParam":{
"firstName":"JOHN",
"lastName":"PAK",
"dob":"",
"driverLicense":"",
"membershipNumber":"",
"phoneNumbers": "null",
"addresses":"null"
}
}
}
案例1 :每当我获得成功的响应时,我都会得到我的rest模板在响应变量中给出的JSON。
public @ResponseBody String mpdValidate(@RequestBody String inputRequest, @RequestHeader String url)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println(inputRequest);
System.out.println(url);
String response = null;
if (url == null || url.isEmpty()) {
url = "myURL";
}
try {
HttpHeaders headers = new HttpHeaders();
headers.set("X-ApplicationContext",
"{\"userId\":\"user\",\"transactionType\":\"realtime\",\"application\":\"app\",\"subSystem\":\"mpd\",\"address\":\"1.0.0.0\",\"correlationId\":\"0f333c\"} ");
HttpEntity<String> request = new HttpEntity<String>(inputRequest, headers);
response = restTemplate.postForObject(url, request, String.class);
} catch (Exception e) {
response = e.getMessage();
}
return response;
}
案例2 :当错误的请求框架且响应失败时,其余模板将返回此响应。
{
"httpCode": 400,
"httpMessage": "Bad Request",
"moreInformation": "Request parameter is null",
"timeStamp": 1539072063795
}
但是响应变量返回null并进入catch块并抛出null指针异常。
我希望将上述JSON格式的字符串格式添加到我的响应变量中。
有人可以帮忙吗?
答案 0 :(得分:1)
try {
// ...
} catch (HttpClientErrorException expection) {
response = expection.getResponseBodyAsString();
}
您需要处理HttpClientErrorException
(或其父RestClientResponseException
)并通过HttpClientErrorException#getResponseBodyAsString
提取响应。
答案 1 :(得分:0)
您应该尝试这样,
// REST Request
try {
restTemplate.postForObject(requestUrl, postBody, Void.class);
} catch (RestException restException) {
Logger.error(this, "RestException: " + restException.getRestError().toString());
response = restException.getRestError().toString();
}