【发布时间】:2016-12-03 21:25:59
【问题描述】:
我有两个 Spring MVC 应用程序通过 Spring Integration HTTP 相互连接。
我有一个“application1”和一个“application2”。
application1 接收到这个 HTTP GET 请求:
http://localhost:8080/application1/api/persons/search/findByName?name=Name
application1 用这个@Controller 管理请求:
@Controller
public class ApplicationController {
@RequestMapping(value = "/api/{repository}/search/{methodName}", method = RequestMethod.GET)
public void search(@PathVariable(value="repository") String repository,
@PathVariable(value="methodName") String methodName,
ModelMap model,
HttpServletRequest request,
HttpServletResponse response) {
// handling the request ...
}
}
这是我可以在请求属性中看到的内容:
getRequestURI=/application1/api/persons/search/findByName
getRequestedSessionId=null
getContextPath=/application1
getPathTranslated=null
getAuthType=null
getMethod=GET
getQueryString=name=Name
getServletPath=/api/persons/search/findByName
getPathInfo=null
getRemoteUser=null
我想“转移”这个请求到 application2 使用带有<int-http:outbound-gateway> 的 Spring Integration HTTP。
outbound-gateway 使用的通道的消息以这种方式起源于@Controller:
MessagingChannel messagingChannel = (MessagingChannel)appContext.getBean("requestChannelBean");
String payload = repository+"/search/"+methodName;
Message<String> message = MessageBuilder.withPayload(payload).build();
MessageChannel requestChannel = messagingChannel.getRequestChannel();
MessagingTemplate messagingTemplate = new MessagingTemplate();
Message<?> response = messagingTemplate.sendAndReceive(requestChannel, message);
这是<int-http:outbound-gateway> 配置:
<int-http:outbound-gateway id="gateway" rest-template="restTemplate"
url="http://localhost:8080/application2/api/service/{pathToCall}"
http-method="POST" header-mapper="headerMapper" extract-request-payload="true"
expected-response-type="java.lang.String">
<int-http:uri-variable name="pathToCall" expression="payload"/>
</int-http:outbound-gateway>
此网关向 url 生成一个 HTTP POST 请求:
http://localhost:8080/application2/api/service/persons/search/findByName
但是在这个请求中我丢失了 application1 收到的原始 QueryString。
我已尝试将 queryString 直接添加到有效负载,如下所示:
String queryString = "";
if (request.getQueryString()!=null)
queryString = request.getQueryString();
String payload = repository+"/search/"+methodName+"?"+queryString;
但这不起作用:生成的 url 是:
http://localhost:8080/application2/api/service/persons/search/findByName%3Fname=Name
“?”符号被“%3F”替换,所以调用的方法是"/service/persons/search/findByName%3Fname=Name",而不是"/service/persons/search/findByName"
我想这取决于http-method="POST";无论如何我都想使用 POST 方法,因为我想将这个“服务”用于一般请求。
那么我要怎么做才能以最简单的方式将原始请求的queryString传递给对方呢?
提前致谢。
【问题讨论】:
-
我想说 application1 的行为是有效的 - 对有效负载进行编码。正确解码应该是 application2 的责任(将
%3F改回?)。您可以控制 application2 吗? -
是的,当然。我可以控制这两个应用程序。
-
这可能会对你有所帮助:stackoverflow.com/q/6138127/466738
-
你说得对,Adam:是 application1 对 URL 进行了编码,我明白为什么。我还找到了避免URI编码的方法:在
<int-http:outbound-gateway>配置中设置encode-uri="false"就足够了(默认为“true”)。
标签: spring spring-mvc spring-integration