我的请求如下:-
http://example.com:8984/service/response?q=bags&source=desktop.search&city.data=mumbai|delhi
如何从url访问这些值,以便获得以下地图:-
{
q => bags,
source => desktop.search,
city.data => [mumbai, delhi]
}
我写了下面的程序:-
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class serviceController {
@RequestMapping("/service/response")
String getSearchString(@RequestParam Map<String, String> params) {
return "SearchString ---- "+params;
}
}
当我在city.data = mumbai中仅给出1个参数时,它工作正常 但是当我给city.data = mumbai | delhi
时遇到错误java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:467) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:294) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) [tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.13.jar:9.0.13]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135) [na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) [na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.13.jar:9.0.13]
at java.base/java.lang.Thread.run(Thread.java:844) [na:na]
请提出正确的方法? 预先感谢
答案 0 :(得分:1)
我建议您以其他方式发送参数,但是如果需要管道字符,则应将其替换为代码%7C
。因此,如果要添加city.data=mumbai|delhi
作为参数,则应将其替换为city.data=mumbai%7Cdelhi
。
之后,您可以使用String方法解析该字段中的参数。
答案 1 :(得分:0)
我认为您可以尝试这样。
@RequestMapping(value = "/test")
@ResponseBody
public void test(@RequestParam Map<String,String> param) {
String[] city = org.springframework.util.StringUtils.split(param.get("city.data"), "|");
System.out.println(Arrays.toString(city));
System.out.println(param);
}
如果只有几个参数,也可以这样尝试。但是请求url应该这样改变。 test2?q = bags&source = desktop.search&city.data = mumbai&city.data = delhi
@RequestMapping(value = "/test2")
@ResponseBody
public void test2(String q, String source, @RequestParam(value = "city.data") String[] city) {
System.out.println(Arrays.toString(city));
System.out.println(source);
System.out.println(q);
}