I have a requirement to use Spring MVC to redirect to an external service using a POST with an object that is built.
From reading this previous question I understand that it is not possible to do so via Spring MVC redirect, so it is required to complete the POST request via a HTTP client in the Java code, which I can do via an example such as the one found here.
I need to be able to redirect the browser to the response of the POST request, but I am not sure how to do so using Spring MVC.
Controller
@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;
}
I can see that the target service is being hit by the POST request successfully, I need to read the output of the response as a return value from the MCV controller as it currently just returns a 404.