我有一个用 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:每当我获得成功响应时,我都会得到与我的其余模板在响应变量中提供的相同的 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 block 抛出空指针异常。
我希望将上述 JSON 字符串格式添加到我的响应变量中。
有人可以帮忙吗?
最佳答案
try {
// ...
} catch (HttpClientErrorException expection) {
response = expection.getResponseBodyAsString();
}
您需要处理HttpClientErrorException
(或其父项 RestClientResponseException
)并通过 HttpClientErrorException#getResponseBodyAsString
提取响应.
关于java - 从字符串变量中的休息服务获取异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52718644/