在Spring MVC中写入文件请求 [英] Write request to file in Spring MVC

查看:126
本文介绍了在Spring MVC中写入文件请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将整个请求写入Spring MVC控制器中的文件。

I'd like to be able to write an entire request to a file within a Spring MVC controller.

我尝试过以下操作,但文件是即使我正在使用大量参数发出POST请求,也总是空的:

I've tried the following, but the file is always empty even though I'm making a POST request with loads of parameters:

    @RequestMapping(method = RequestMethod.POST, value = "/payments/confirm")
public void receiveCallback(ServletInputStream inputStream)
{
    try
    {
        inputStream.reset();
        byte[] data = IOUtils.toByteArray(inputStream);

        File file = new File(System.getProperty("java.io.tmpdir") + "test" + System.currentTimeMillis() + ".txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data);
        fos.close();
    }
    catch (Exception e)
    {
        logger.error("Error writing request", e);
    }
}

我也尝试过使用HttpServletRequest.getInputStream() ,但结果相同。

I've also tried using HttpServletRequest.getInputStream(), but the same results.

推荐答案

使用InputStream不起作用(参见BalusC的回答)。下面是一个如何使用HTTPServletRequest对象来编写标题和参数的示例:

Using the InputStream won't work (see BalusC's answer). Here's a sample of how you could use a HTTPServletRequest object instead to write headers and parameters:

@RequestMapping(method = RequestMethod.POST, value = "/payments/confirm")
public void receiveCallback(HttpServletRequest request) {
    try {
        StringBuilder sb = new StringBuilder();
        sb.append("Headers:\n");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(headerName);
            while (headers.hasMoreElements()) {
                String headerValue = headers.nextElement();
                sb.append(headerName).append(':').append(headerValue).append('\n');
            }
        }
        sb.append("\nParameters:\n");
        for(Entry entry: (Set<Entry>) request.getParameterMap().entrySet(){
            sb.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
        }
        byte[] data = sb.toString().getBytes();

        File file = new File(System.getProperty("java.io.tmpdir") + "test"
                + System.currentTimeMillis() + ".txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data);
        fos.close();
    } catch (Exception e) {
        logger.error("Error writing request", e);
    }
}

这篇关于在Spring MVC中写入文件请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆