【发布时间】:2017-03-15 22:02:17
【问题描述】:
我需要使用 Spring MVC 使用带有已构建对象的 POST 重定向到外部服务。
通过阅读this previous question,我了解到无法通过 Spring MVC 重定向执行此操作,因此需要通过 Java 代码中的 HTTP 客户端完成 POST 请求,我可以通过示例来完成,例如找到here的那个。
我需要能够将浏览器重定向到 POST 请求的响应,但我不确定如何使用 Spring MVC 来做到这一点。
控制器
@RequestMapping(method = RequestMethod.GET, value = "/handoff")
public HttpEntity dispatch(HttpServletRequest request,
@RequestParam(value = "referralURL", required = false) String referralUrl) {
String redirectURL = "http://desinationURL.com/post";
HttpClientHelper httpHelper = new HttpClientHelper();
HttpEntity entity = httpHelper.httpClientPost(redirectURL, null);
// Redirect
return entity;
}
HttpClientHelper.java
public HttpEntity httpClientPost(String url, List<NameValuePair> params) throws ClientProtocolException, IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
// Request parameters and other properties.
if (params != null) {
httppost.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODING));
}
// Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
return entity;
}
我可以看到目标服务被 POST 请求成功命中,我需要从 MCV 控制器读取响应的输出作为返回值,因为它当前只返回 404。
【问题讨论】:
标签: java spring spring-mvc redirect apache-httpclient-4.x