Java 如何在Restlet中发送错误响应?

Java 如何在Restlet中发送错误响应?,java,web-services,rest,restlet,Java,Web Services,Rest,Restlet,我有一个RestletServerResource,它应该使用参数user处理GET请求。如果user等于某个值,它应该返回某个图像,否则将发送错误响应(404或403),指示不允许发送方获取图像 import org.restlet.data.MediaType; import org.restlet.representation.ObjectRepresentation; import org.restlet.representation.Representation; import org

我有一个Restlet
ServerResource
,它应该使用参数
user
处理GET请求。如果
user
等于某个值,它应该返回某个图像,否则将发送错误响应(404或403),指示不允许发送方获取图像

import org.restlet.data.MediaType;
import org.restlet.representation.ObjectRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

public class GetMap extends ServerResource {
    @Get
    public Representation getImage() {
        final String user = getQuery().getValues("user");

        if (user.equals("me")) {
            //Read map from file and return it
            byte[] data = readImage();
            final ObjectRepresentation<byte[]> or=new ObjectRepresentation<byte[]>(data, MediaType.IMAGE_PNG) {
                @Override
                public void write(OutputStream os) throws IOException {
                    super.write(os);
                    os.write(this.getObject());
                }
            };
            return or;
        }
        return null; // Here I want to send an error response
    }
    [...]
}
import org.restlet.data.MediaType;
导入org.restlet.representation.ObjectRepresentation;
导入org.restlet.representation.representation;
导入org.restlet.resource.Get;
导入org.restlet.resource.ResourceException;
导入org.restlet.resource.ServerResource;
公共类GetMap扩展了ServerResource{
@得到
公共代表getImage(){
最终字符串user=getQuery().getValues(“用户”);
if(user.equals(“me”)){
//从文件中读取地图并返回它
字节[]数据=readImage();
最终ObjectRepresentation or=新的ObjectRepresentation(数据,MediaType.IMAGE\u PNG){
@凌驾
公共无效写入(OutputStream os)引发IOException{
super.write(操作系统);
write(this.getObject());
}
};
返回或返回;
}
return null;//这里我想发送一个错误响应
}
[...]
}

如何在
getImage
方法(而不是
returnnull
)中发送标准化错误响应?

查看
ServerResource\setStatus(Status)
和其他重载方法。它允许您返回自定义正文以及所需的HTTP状态

或者抛出一个
新的ResourceException
(),框架将把它们转换为正确的HTTP状态并提供一条默认消息,尽管这不太可能是一个映像


这应该能满足你的需要。JavaDoc链接到2015年11月25日的2.3.x版

过去,我写过一篇关于这一点的博客文章:

  • 使用Restlet处理异常:
除了伟大的Caleryn的答案之外,现在还有
@Status
注释,用于在Restlet中使用自定义异常。样本:

@Status(value = 400, serialize = true)
public class MyValidationException extends RuntimeException {
    public ServiceValidationException(String message, Exception e) {
        super(message, e);
    }
}
当抛出这样的异常时,Restlet会自动检测它并创建相应的错误消息。在示例中,是一个状态代码为
400
的响应,它尝试使用转换器服务将异常序列化为一个bean到JSON(或其他内容)

希望它能帮助你, 蒂埃里