本文介绍了Restlet:如何通过设置自定义MediaType检索DTO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为具有自定义MediaType的实体发送GET请求?

How can I send GET request for entity with custom MediaType?

例如,我想检索MyUserDTO并将MediaType设置为application/user+yml.

For example I want to retrieve MyUserDTO and set MediaType to application/user+yml.

目前,我有两个分开的动作.我可以检索实体:

For now I have two separated actions. I can retrieve entity:

resource.get(MyUserDTO.class);

并可以检索字符串:

resource.get(new MediaType("application", "user+yml");

但是如何将它们结合起来呢?或者,也许有一些技巧可以配置Restlet来教他如何使用自定义MediaType.

But how to combine them? Or maybe there is some trick to configure Restlet to teach him how to work with custom MediaTypes.

推荐答案

实际上,您有正确的方法,但没有使用类MediaType(new MediaType(name, description))的正确构造函数.

In fact, you have the right approach but you don't use the right constructor of the class MediaType (new MediaType(name, description)).

要使代码正常工作,您需要将其更改为此:

To make your code work, you need to change it to this:

resource.get(new MediaType("application/user+yml"));

在服务器端,您将获得以下信息:

On the server side, you will get this:

@Get
public Representation getSomething() {
    System.out.println(">> media types = " +
    getRequest().getClientInfo().getAcceptedMediaTypes());
    // Display this: media types = [application/user+yml:1.0]
    (...)
}

您可以通过在注释Get中添加一个值来利用Restlet的扩展支持.对于您的情况,您需要按如下所述添加自定义扩展名:

You can leverage the extension support of Restlet by adding a value within the annotation Get. In your case, you need to add a custom extension as described below:

public class MyApplication extends Application {
    public MyApplication() {
        getMetadataService().addExtension(
            "myextension", new MediaType("application/user+yml"));
        (...)
    }

    @Override
    public Restlet createInboundRoot() {
        (...)
    }
}

现在,您可以在服务器资源中使用扩展名:

Now you can use the extension within your server resource:

@Get("myextension")
public Representation getSomething() {
    (...)
}

此方法将与预期的介质类型为application/user+yml一起使用.

This method will be used with the expected media type is application/user+yml.

希望它对您有帮助,蒂埃里

Hope it helps you,Thierry

这篇关于Restlet:如何通过设置自定义MediaType检索DTO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 06:37