java - 发布 xml 文档,但不是通过请求参数而是在正文中

标签 java servlets spring-mvc

我目前使用以下方法将 xml 文件发布到网址:

HttpClient client = new HttpClient();
HttpPost post = new HttpPost("http://www.example.com/post/here");

File f = new File("/path/to/file/file.txt");
String str = Files.toString(f, Charset,defaultCharset());

List<NameValuePair> nvp = new ArrayList<NameValuePair>(1);
nvp.add(new BasicNameValuePair("payload", xmlFile));

post.setEntity(new UrlEncodedFormEntity(nvp));

HttpResponse response = client.execute(post);

但这会添加一个“payload”请求参数,这样当我想在 doPost servlet 中接收该值时,我会这样做:

request.getParameter("payload");

我猜这个参数“payload”位于请求 header 中?

我想要做的是在请求正文中发送此文件,因此在我的 doPost 中我必须从流中获取数据,即:

... = request.getInputStream();

如何修改我的代码来做到这一点? (使用httpclient)

另外,有人可以解释一下两者在请求格式方面的区别吗?

最佳答案

Apache documentation on HttpClient有一个请求中流数据的示例:

public class FileRequestEntity implements RequestEntity {

    private File file = null;

    public FileRequestEntity(File file) {
        super();
        this.file = file;
    }

    public boolean isRepeatable() {
        return true;
    }

    public String getContentType() {
        return "text/plain; charset=UTF-8";
    }

    public void writeRequest(OutputStream out) throws IOException {
        InputStream in = new FileInputStream(this.file);
        try {
            int l;
            byte[] buffer = new byte[1024];
            while ((l = in.read(buffer)) != -1) {
                out.write(buffer, 0, l);
            }
        } finally {
            in.close();
        }
    }

    public long getContentLength() {
        return file.length();
    }
}

File myfile = new File("myfile.txt");
PostMethod httppost = new PostMethod("/stuff");
httppost.setRequestEntity(new FileRequestEntity(myfile));

两者的区别在于,它们都是将数据存储在HTTP请求的body中。作为example ,以下是一个标准 HTTP POST 请求,带有两个 URL 编码参数(homefavoriteflavor)。直接使用输入流也会稍微高效一些,因为不需要解析参数。

POST /path/script.cgi HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies

关于java - 发布 xml 文档,但不是通过请求参数而是在正文中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10270005/

相关文章:

java - 将 .dmp 文件转换为 .hprof 文件

java - 来自线程/堆栈跟踪的 session ID

java - 使用 Java 获取服务器的编码

Java Spring JDBC模板问题

spring - 如何使用spring 3将xml映射到带有rest模板的pojo类?

java - 如何在spring sts中获取spring boot web项目的默认结构?

java - Hibernate 过滤器的 JPA 等效项

java.lang.ClassCastException : com. tibco.tibjms.TibjmsxSessionImp 无法转换为 javax.jms.QueueSession

java - 未为 HttpServletResponse 设置 header

javascript - 如何在不提交的情况下调用spring Controller