重定向使用和POST参数

时间:2019-06-15 12:54:09

标签: 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 {

    String url = "http://www.someserver.com";
    String post_token = "1234561234543322";

    // Open here the link and redirect the

    return new ModelAndView("redirect:" + url); 
}

我如何打开此链接,将post_token作为POST参数发送,然后将打开的页面返回给用户?

是否有某种方法可以为用户实施此解决方案? 作为第二种解决方案,我可以将此页面返回给用户并包含post_token作为参数吗?

3 个答案:

答案 0 :(得分:1)

您可以使用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请求代码。

答案 1 :(得分:0)

您实际上必须向外部服务器发出发布请求(例如,使用Apache HttpClient或在简单情况下使用JSoup),然后将响应正文返回给原始调用者。

如果您要代表用户执行某种登录操作,则还必须执行受控的会话劫持。

答案 2 :(得分:0)

要请求重定向用户的浏览器,您需要发送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' });
相关问题