【问题标题】:HttpMediaTypeNotAcceptableException: Could not find acceptable representation. When with special urlHttpMediaTypeNotAcceptableException:找不到可接受的表示。使用特殊网址时
【发布时间】:2016-06-29 11:29:54
【问题描述】:
    @RequestMapping(value = "/servers/{domain}", method = RequestMethod.GET)
    public Server getMailServer(@PathVariable("domain") String domain)

    Server server = null;
    try {
        server = getServerByDomain(domain);
    }
    catch(Exception e){

    }
     return server;
    }

当我用 HttpClient Get 方法调用“http://localhost:8080/server/hotmail.com”时,变量域的值是“hotmail”,而不是“hotmail.com”。我得到了错误: HttpMediaTypeNotAcceptableException: 找不到可接受的表示。

但如果我打电话给“http://localhost:8080/server/hotmail”,效果很好。

我希望有人能看看是什么导致了这个问题。

【问题讨论】:

标签: spring-mvc


【解决方案1】:

这可能与我遇到的问题相同(还有这个人:https://stick2code.blogspot.co.at/2014/03/solved-orgspringframeworkwebhttpmediaty.html

我的服务提供对文件的操作,即 /files/check/foo.txt

我总是得到一个 HttpMediaTypeNotAcceptableException 并且我的休息处理程序从未真正被调用过。

问题是,Spring 有一个特性,它会尝试通过路径扩展来检测请求的内容类型。所以 .com 可能意味着一个 COM 文件。 (见http://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#mvc-config-content-negotiationhttp://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#mvc-config-path-matching

我最小的@Config 修复:

@Configuration
@EnableWebMvc
public class PathDispatchConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false);
        configurer.setUseRegisteredSuffixPatternMatch(false);
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}

【讨论】:

    【解决方案2】:

    将您的@RequestMapping 更改为以下:)

    @RequestMapping(value = "/servers/{domain:.+}", method = RequestMethod.GET)
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,因为我的请求网址中有用户名(=邮件地址)。感谢 Benjamin Maurer 的帖子,我发现了问题。但是,我以不同的方式修复了它,因为我不确定他的答案安全性的后果。 我在请求中添加了用户名作为请求参数。在你的情况下,这看起来像:

          @RequestMapping(value = "/servers", method = RequestMethod.GET)
          public Server getMailServer(@RequestParam("domain") String domain) {
              // do stuff
          }
      

      然后,请求 URL 将类似于: http://localhost:8080/server?domain=hotmail.com

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-08
        • 2013-08-08
        • 1970-01-01
        • 2022-10-20
        相关资源
        最近更新 更多