【问题标题】:How to control the HTTP response code from a Restlets resource?如何控制来自 Restlets 资源的 HTTP 响应代码?
【发布时间】:2017-12-25 07:08:52
【问题描述】:

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

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 返回将由带有 200 HTTP 响应代码的 Restlet 自动处理。

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

【问题讨论】:

    标签: java servlets http-status-codes restlet-2.0


    【解决方案1】:

    据我所知,有一个名为 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 的新手

    【讨论】:

    • 你能拿我上面的代码 sn-p 来回答吗?您基本上说“是的,我们可以返回 HTTP 代码”,但您没有向我们展示如何做到这一点。
    • 让我打开我的电脑,并为您提供我所做的一些工作的示例。 30分钟,你就会拥有它
    猜你喜欢
    • 2018-07-05
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2011-01-14
    • 2015-05-24
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多