gpt4 book ai didi

Java:REST 服务中的异常和返回值处理消耗

转载 作者:行者123 更新时间:2023-12-02 03:25:40 25 4
gpt4 key购买 nike

我正在调用返回 JSON 字符串的 REST 服务。它有效,但我不确定如何处理异常和返回值。这是我写的两个方法:

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;
}
}

我的返回值和异常处理可以吗?或者有更好的方法吗?

最佳答案

为了更好的客户端处理,您应该有一个带有返回情况的 Enum例如,如果我们正在构建一个注册模块,您的枚举应该如下所示:

 public enum RestResponseEnum{
DONE(1,"done"),DUPLICATE_RECORD(2,"Sorry this is a duplicate record"),ERROR(3,"There is an error happened")
//Getter & Setter
private int code;
//Getter & Setter
private String msg;

private(int code,String msg){
this.code=code;
this.msg=msg;
}


public static String getAsJson(RestResponseEnum restResponseEnum){
JSONObject jsonObject=new JSONObject();
jsonObject.put("code", restResponseEnum.getCode());
jsonObject.put("message", restResponseEnum.getMsg());
return jsonObject.toString();
}
}

像这样使用它:

{
// Your function code
if(registeredEmailIsFoundInDatabase){
return RestResponseEnum.getAsJson(RestResponseEnum.DUPLICATE_RECORD);
}
}

您应该始终促进并明确对客户的答复你可以从处理大多数 api 中看到这种方法,比如 github 上的这个:https://api.github.com/users/any/any

关于Java:REST 服务中的异常和返回值处理消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38941229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com