我正在使用Java中的HttpClient库编写REST Client。
我编写了此方法来发布对象:
public HttpResponse post(URIBuilder uri, Object body) {
HttpPost request = new HttpPost(setBaseProps(uri));
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
HttpResponse response = null;
try {
StringEntity bodyToPost = new StringEntity(g.toJson(body));
request.setEntity(bodyToPost);
log.info("Perform POST request to: " + request.getURI().toString());
response = client.execute(request);
} catch (UnsupportedEncodingException e) {
log.error("The Character Encoding is not supported!");
e.printStackTrace();
} catch (ClientProtocolException e) {
log.error("HTTP protocol error!");
e.printStackTrace();
} catch (IOException e) {
log.error("Some problems occur or the connection was aborted!");
e.printStackTrace();
}
return response;
}
private URI setBaseProps(URIBuilder uri) {
URI built = null;
uri.setScheme(props.protocol())
.setHost(props.host())
.setPort(props.port());
try {
built = uri.build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return built;
}
所有方法都在方法签名中引发检查的异常。并且如果其中一些异常将被缓存,则HttpResponse
将是null
,可以在服务NullPointerException
上产生。
如何避免这种情况?
将响应包装到Optional并在服务中检查它是否很好?
谢谢!
答案 0 :(得分:1)
将响应对象从一个类传递到另一个类不是一个好主意,最好构建一个DTO并将其返回给调用类。
如果您需要返回响应对象,则可以: