Java 重定向使用和发布参数
我想用Spring实现这个示例:Java 重定向使用和发布参数,java,spring,spring-boot,Java,Spring,Spring Boot,我想用Spring实现这个示例: @PostMapping(value = "/redirect/to_payment/{token}") public ModelAndView handleRedirectMessage(@PathVariable("token") String token, @RequestBody Transaction transaction, HttpServletRequest request) throws Exception { Str
@PostMapping(value = "/redirect/to_payment/{token}")
public ModelAndView handleRedirectMessage(@PathVariable("token") String token,
@RequestBody Transaction transaction, HttpServletRequest request) throws Exception {
String url = "http://www.someserver.com";
String post_token = "1234561234543322";
// Open here the link and redirect the
return new ModelAndView("redirect:" + url);
}
如何打开此链接,将post_令牌作为post参数发送,并将打开的页面返回给用户
是否有一些方法可以为用户实现此解决方案?
作为第二种解决方案,我可以将此页面返回给用户,并将
post_令牌作为参数包含进去吗?您必须实际向外部服务器发出post请求(例如,使用Apache HttpClient或对于简单情况下的JSoup),并将响应正文返回给原始调用方
如果您想代表用户执行一种eg登录,您还必须执行受控会话劫持。您可以使用okhttp3依赖项,从服务器发送http请求,然后将okhttp对象的响应主体返回给客户端
以下是一个例子:
@PostMapping(value = "/redirect/to_payment/{token}")
public ModelAndView handleRedirectMessage(@PathVariable("token") String token,
@RequestBody Transaction transaction, HttpServletRequest request) throws Exception {
String url = "http://www.someserver.com";
String post_token = "1234561234543322";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(null) // because u have no body
.addHeader("Authorization", post_token)
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
return new ModelAndView(response.body().toString()); // or something like this
}
当然,您必须处理IOException
,最后的body方法可能有点不同
一个提示:您可以使用postman通过模拟您的请求轻松地为您生成OkHttp或Unirest请求代码。要请求重定向用户的浏览器,您需要发送JS代码和页面加载事件,您必须像这样调用重定向代码
function redirectPost(url, data) {
var form = document.createElement('form');
document.body.appendChild(form);
form.method = 'post';
form.action = url;
for (var name in data) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = data[name];
form.appendChild(input);
}
form.submit();
}
// call on window load
redirectPost('http://www.someserver.com', { post_token: '1234561234543322' });
@Martencacher不,他想代理这个电话,用RestTemplate@ThomasAndolf你能给我看一下代码示例吗?谷歌如何使用resttemplate,大约有一百万个示例。然后尝试自己实现一个解决方案。如果你被困在帖子里,你已经走了多远,还有一些具体的问题。我不会写你的代码。