如何通过Spring Boot/Tomcat发送带有GET参数的JSON? [英] How to send json with GET params via Spring Boot / Tomcat?

查看:80
本文介绍了如何通过Spring Boot/Tomcat发送带有GET参数的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我目前正在开发一个项目,该项目中的产品对象依次包含来源"对象(包含 region:String country:String ).

我想做的是一个RestController,它带有一个可选 Origin对象,并对其进行一些处理(例如,记录它).

这就是我现在拥有的:

  @GetMapping(搜索")公共页面< Wine>getProductByStuff(@RequestParam(required = false)原点原点,/*其他属性*/){log.info(来源);//它具有适当的toString方法.} 

此方法有两个问题.首先,当我发送如下请求时:

http://[...]/search?origin = {"region":"blah","country":"UK"}

,甚至是html转换后的字符串,例如:

http://[...]/search?origin = {%22region%22:%22blah%22%44%22country%22:%22UK%22}

...它说

在请求目标[/api/products/search?origin = {%22region%22:%22blah%22%44%22country%22:%22DE%22}]中找到无效字符.有效字符在RFC 7230和RFC 3986中定义.

Afaik Tomcat需要的唯一有效字符是{}.我用html编码字符替换的所有其他字符仍然无法正常工作.

我为防止这种情况所做的事情:

  @Component公共类TomcatWebServerCustomizer实现WebServerFactoryCustomizer< TomcatServletWebServerFactory>{@Override公共无效custom(TomcatServletWebServerFactory工厂){TomcatConnectorCustomizer a = null;factory.addConnectorCustomizers(connector-> {connector.setAttribute("relaxedPathChars",<> [\\] ^`{|},\"));connector.setAttribute("relaxedQueryChars",<> [\\] ^`{|},\"));});}} 

(请参见

注意

我的回答不是在辩论您应该使用 POST 还是 GET ,因为这不是您所要的.如果要发送一些有效载荷作为查询参数,它只是提供一种选择

so currently I'm working on a project where we have product objects which in turn contain "Origin" objects (containing region: String and country: String).

What I'm trying to do is a RestController which takes in an optional Origin object and does something with it (e.g. logs it).

This is what I have right now:

@GetMapping("search")
    public Page<Wine> getProductByStuff(
            @RequestParam(required = false) Origin origin, 
            /* other attributes */) {
    log.info(origin); // it has a proper toString method.
}

There are two problem with this approach. First of all, when I send a request like:

http://[...]/search?origin={"region":"blah","country":"UK"}

or even the html converted string like:

http://[...]/search?origin={%22region%22:%22blah%22%44%22country%22:%22UK%22}

... it says

Invalid character found in the request target [/api/products/search?origin={%22region%22:%22blah%22%44%22country%22:%22DE%22}]. The valid characters are defined in RFC 7230 and RFC 3986.

Afaik the only valid characters Tomcat has that I need are {}. All others I've replaced with the html encoded chars and it still doesn't work.

What I did to prevent this:

@Component
public class TomcatWebServerCustomizer
        implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        TomcatConnectorCustomizer a = null;
        factory.addConnectorCustomizers(connector -> {
            connector.setAttribute("relaxedPathChars", "<>[\\]^`{|},\"");
            connector.setAttribute("relaxedQueryChars", "<>[\\]^`{|},\"");
        });
    }
}

(See this, which is, by the way, deprecated (at least connector.setAttribute).)

This produced:

MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type '[censored].backend.model.Origin'.

My questions are:

  • (How) is it possible to configure Tomcat/Spring so that they can actually accept json in the url params?
  • How would I format it in e.g. Postman so that it would work? Currently I'm just converting special characters by hand in the params tab of Postman.

解决方案

  • Here is what you need to do if you want to send it as json query param.

     @RestController
     public class OriginController {

      @GetMapping("/search")
      public void getOrigin(@RequestParam(value = "origin", required = false) 
                            Origin origin) {
        System.out.println(origin);
      }

     }

  • Register a converter

    @Component
   public class StringToOriginConverter implements 
                              Converter<String, Origin> {

      ObjectMapper objectMapper = new ObjectMapper();

      @Override
      public Origin convert(String source) {
         try {
            return objectMapper.readValue(source, Origin.class);
         } catch (JsonProcessingException e) {
            //You could throw some exception here instead for custom error
            return null;
         }

       }
    }

  • Sending from postman

Note

My answer is not debating whether you should use POST or GET as it is not what you have asked. It is just providing one option if you want to send some payload as query param

这篇关于如何通过Spring Boot/Tomcat发送带有GET参数的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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