Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringMVC重定向,带有来自HTTP POST的响应_Java_Spring_Spring Mvc_Redirect_Apache Httpclient 4.x - Fatal编程技术网

Java SpringMVC重定向,带有来自HTTP POST的响应

Java SpringMVC重定向,带有来自HTTP POST的响应,java,spring,spring-mvc,redirect,apache-httpclient-4.x,Java,Spring,Spring Mvc,Redirect,Apache Httpclient 4.x,我需要使用SpringMVC重定向到一个外部服务,使用一个包含已构建对象的POST 通过阅读,我了解到不可能通过SpringMVC重定向来完成POST请求,因此需要通过Java代码中的HTTP客户机完成POST请求,我可以通过一个示例(如找到的示例)来完成 我需要能够将浏览器重定向到POST请求的响应,但是我不知道如何使用SpringMVC来实现 控制器 @RequestMapping(method = RequestMethod.GET, value = "/handoff") public

我需要使用SpringMVC重定向到一个外部服务,使用一个包含已构建对象的POST

通过阅读,我了解到不可能通过SpringMVC重定向来完成POST请求,因此需要通过Java代码中的HTTP客户机完成POST请求,我可以通过一个示例(如找到的示例)来完成

我需要能够将浏览器重定向到POST请求的响应,但是我不知道如何使用SpringMVC来实现

控制器

@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;

}
公共HttpEntity httpClientPost(字符串url,列表参数)抛出ClientProtocolException,IOException{ HttpClient HttpClient=HttpClients.createDefault(); HttpPost HttpPost=新的HttpPost(url); //请求参数和其他属性。 如果(参数!=null){ setEntity(新的UrlEncodedFormEntity(参数,常量.UTF_8_编码)); } //执行并获得响应。 HttpResponse response=httpclient.execute(httppost); HttpEntity=response.getEntity(); 返回实体; }
我可以看到目标服务被POST请求成功命中,我需要从MCV控制器读取响应的输出作为返回值,因为它当前只返回404

使用sendRedirect而不是HttpClient,控制器方法如下所示

@RequestMapping(method = RequestMethod.GET, value = "/handoff")
public HttpEntity dispatch(HttpServletRequest request, HttpServletResponse response,
  @RequestParam(value = "referralURL", required = false) String referralUrl) {

    String redirectURL = "http://desinationURL.com/post";

    response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
    response.setHeader("Location", redirectURL);

    // Redirect
    return entity;
}
无法将浏览器重定向到POST请求的响应。您所能做的就是将调用结果发送回外部URL。或者以某种方式处理响应,然后转发到应用程序中的其他页面,该页面显示有关响应的一些信息

e、 g


如果您对更复杂的解决方案感兴趣,您可以利用Zuul实现这一点,并让Zuul管理请求转发。在筛选链期间,您可以根据需要操纵请求。

我就是这样做的

    CloseableHttpClient httpClient = HttpClients.custom()
            .setRedirectStrategy(new LaxRedirectStrategy())
            .build();

    //this reads the input stream from POST
    ServletInputStream str = request.getInputStream();

    HttpPost httpPost = new HttpPost(path);
    HttpEntity postParams = new InputStreamEntity(str);
    httpPost.setEntity(postParams);

    HttpResponse httpResponse = null ;
    int responseCode = -1 ;
    StringBuffer response  = new StringBuffer();

    try {

        httpResponse = httpClient.execute(httpPost);

        responseCode = httpResponse.getStatusLine().getStatusCode();
        logger.info("POST Response Status::  {} for file {}  ", responseCode, request.getQueryString());

        //return httpResponse ;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));

        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        logger.info(" Final Complete Response {}  " + response.toString());
        httpClient.close();

    } catch (Exception e) {

        logger.error("Exception ", e);

    } finally {

        IOUtils.closeQuietly(httpClient);

    }

    // Return the response back to caller
    return  new ResponseEntity<String>(response.toString(), HttpStatus.ACCEPTED);
CloseableHttpClient-httpClient=HttpClients.custom()
.setRedirectStrategy(新的LaxRedirectStrategy())
.build();
//这将从POST读取输入流
ServletInputStream str=request.getInputStream();
HttpPost HttpPost=新的HttpPost(路径);
HttpEntity后参数=新输入流实体(str);
httpPost.setEntity(后参数);
HttpResponse HttpResponse=null;
int-responseCode=-1;
StringBuffer响应=新的StringBuffer();
试一试{
httpResponse=httpClient.execute(httpPost);
responseCode=httpResponse.getStatusLine().getStatusCode();
info(“文件{}的响应后状态:{}”,响应代码,request.getQueryString());
//返回httpResponse;
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
httpResponse.getEntity().getContent());
字符串输入线;
而((inputLine=reader.readLine())!=null){
追加(inputLine);
}
reader.close();
info(“最终完整响应{}”+响应.toString());
httpClient.close();
}捕获(例外e){
错误(“异常”,e);
}最后{
IOUtils.closeclient(httpClient);
}
//将响应返回给调用者
返回新的ResponseEntity(response.toString(),HttpStatus.ACCEPTED);

我已经包含了HttpServletResponse,并按照建议设置了状态和标题值,但是它没有重定向,仍然返回404。我是否需要更改返回响应的方法而不是HttpEntity?
    CloseableHttpClient httpClient = HttpClients.custom()
            .setRedirectStrategy(new LaxRedirectStrategy())
            .build();

    //this reads the input stream from POST
    ServletInputStream str = request.getInputStream();

    HttpPost httpPost = new HttpPost(path);
    HttpEntity postParams = new InputStreamEntity(str);
    httpPost.setEntity(postParams);

    HttpResponse httpResponse = null ;
    int responseCode = -1 ;
    StringBuffer response  = new StringBuffer();

    try {

        httpResponse = httpClient.execute(httpPost);

        responseCode = httpResponse.getStatusLine().getStatusCode();
        logger.info("POST Response Status::  {} for file {}  ", responseCode, request.getQueryString());

        //return httpResponse ;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));

        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        logger.info(" Final Complete Response {}  " + response.toString());
        httpClient.close();

    } catch (Exception e) {

        logger.error("Exception ", e);

    } finally {

        IOUtils.closeQuietly(httpClient);

    }

    // Return the response back to caller
    return  new ResponseEntity<String>(response.toString(), HttpStatus.ACCEPTED);