Ich rufe einen REST-Service, der eine JSON-String zurückgibt. Es funktioniert, aber ich bin nicht sicher, wie mit den Ausnahmen umzugehen und Werte zurückzugeben. Hier sind meine zwei Methoden, die ich schrieb:Java: Exception und Return Value-Behandlung in REST-Service konsumieren
public static String callRestService(String id) {
try {
URL url = new URL("http://"localhost:8080/rest/api/2/issue/" + id);
String basicAuth = ConnectionHelper.getServerAuthentication(serverConfig.get("authenticationType"),
serverConfig.get("username"), serverConfig.get("password"));
HttpURLConnection connection = ConnectionHelper.getHttpURLConnection(url, "GET", "Accept", basicAuth);
if (connection != null) {
InputStream responseStream = connection.getInputStream();
String response = StringHelper.convertInputStreamToString(responseStream);
connection.disconnect();
return response;
}
return "";
} catch (Exception e) {
return "";
}
}
public static HttpURLConnection getHttpURLConnection(URL url, String requestMethod, String requestProperty,
String authentication) {
try {
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
if (authentication != null && !authentication.isEmpty()) {
connection.addRequestProperty("Authorization", authentication);
}
connection.setRequestMethod(requestMethod);
connection.addRequestProperty(requestProperty, "application/json");
return connection;
} catch (Exception e) {
return null;
}
}
Ist mein Rückgabewert und Ausnahmebehandlung ok? Oder gibt es einen besseren Weg, dies zu tun?
Sie sollten 'disconnect' innerhalb eines 'finally'-Blocks aufrufen, so dass es auch im Fehlerfall aufgerufen wird. – johnnyaug
Ok, du hast Recht. Was ist mit Ausnahmen und den Rückgabewerten im Fehlerfall? – SpaceJump
Es liegt an Ihnen, wie Sie mit Ausnahmen umgehen und was Sie in solchen Fällen zurückgeben möchten. Im Allgemeinen sollten Sie Ausnahmen protokollieren, damit Sie wissen, dass sie aufgetreten sind. – johnnyaug