如何从Restlets资源控制HTTP响应代码?

问题描述 投票:1回答:1

我目前正在使用Restlets框架,我找不到在服务方法中手动设置HTTP响应代码的方法。请考虑以下代码段:

public class MyResource extends ServerResource {
    @Post("json")
    public Representation doSomething(Representation entity) throws IOException {
        int status = 200;
        try {
            // do something which might throw an exception
        }
        catch (Exception e) {
            // log the exception
            // *** I would like to assign HTTP status 500 here ***
            status = 500;
        }

        JSONObject responseJSON = new JSONObject();
        responseJSON.put("result", "some data");
        Representation rep = new JsonRepresentation(responseJSON.toJSONString());

        return rep;
    }
}

我有能力捕获并记录异常,如果发生异常,但我不清楚如何更改HTTP响应代码。据我所知,从doSomething返回将由Restlets自动处理200 HTTP响应代码。

我知道如何直接从过滤器或servlet分配状态代码,但是可以在Restlets中执行此操作,而无需沿着servlet层进行操作吗?

java servlets http-status-codes restlet-2.0
1个回答
0
投票

据我所知,有一个名为ResponseEntity的对象,您可以使用它来操作微服务和请求 - 响应编程模型,它允许您指定返回的HTTP返回码。但是,您需要实体,我认为这低于您的Servlet抽象级别。

您可以将它们更改为某些预定义的值,例如HTTP.INTERNAL_SERVER_ERROR等,它们最终会转换为最终的值。

我希望这有一些帮助

编辑:

导入ResponseEntity对象的必要资源。在STS,它是

import org.springframework.http.ReponseEntity;
import org.springframework.http.HttpStatus;

public class MyResource extends ServerResource {
@Post("json")
public ResponseEntity<Representation> doSomething(Representation entity) throws IOException {
    int status = 200;
    try {
        // do something which might throw an exception
    }
    catch (Exception e) {
        ResponseEntity<Representation> response = null;
        response = new ResponseEntity<Representation>(HttpStatus.INTERNAL_SERVER_ERROR);
        return response;
    }

    JSONObject responseJSON = new JSONObject();
    responseJSON.put("result", "some data");
    Representation rep = new JsonRepresentation(responseJSON.toJSONString());

    return rep;
}

抱歉延误了。我是Stack Overflow的新手

© www.soinside.com 2019 - 2024. All rights reserved.