如何从请求中获取 MediaType [英] How to get MediaType from Request

查看:160
本文介绍了如何从请求中获取 MediaType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Restlet 构建某种代理服务器,但是我遇到了一个问题,即无法根据客户端请求自动确定 MediaType.

I'm building some kind of proxy server with Restlet, however I am having a problem that there's no automatic way to determine the MediaType based on the client request.

这是我的代码:

Representation entity = null;
entity.setMediaType(processMediaType(path));

处理媒体类型:

private MediaType processMediaType(String path){
    MediaType type = MediaType.ALL;
    if(path.endsWith("html")){
        type = MediaType.TEXT_HTML;
    } else if (path.endsWith("css")) {
        type = MediaType.TEXT_CSS;
    } else if (path.endsWith("js")) {
        type = MediaType.TEXT_JAVASCRIPT;
    } else if (path.endsWith("txt")) {
        type = MediaType.TEXT_PLAIN;
    } else if (path.endsWith("jpg")){
        type = MediaType.IMAGE_JPEG;
    } else if (path.endsWith("png")){
        type = MediaType.IMAGE_PNG;
    }
    return type;
}

我想知道 MediaType 是否可以由框架自动构造(或通过从请求中获取 MediaType,这对我不起作用)来自请求,这样我就不需要执行这些 if-else 语句这在捕捉各种媒体类型方面非常有限.

I was wondering if the MediaType can be constructed automatically by the framework (or by getting the MediaType from the request, which didn't worked for me) from the request such that I will not need to do these if-else statements which is very much limited in catching various media types.

推荐答案

Restlet 根据 Content-Type 标头获取请求的媒体类型.要值,可以用这个:

Restlet get the media type of the request based on the Content-Type header. To the value, you can use this:

MediaType mediaType = getRequest().getEntity().getMediaType();

ClientInfo 的媒体类型提示对应于 Accept 标头中提供的内容:

The media type hints of the ClientInfo corresponds to what is provided within the Accept header:

getRequest().getClientInfo().getAcceptedMediaTypes();

要获取 Restlet API 中标头的映射,您可以查看此链接:

To get the mapping of headers in the Restlet API, you could have a look at this link:

这篇关于如何从请求中获取 MediaType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆