在Java

时间:2018-01-23 20:58:09

标签: java apache http multipart

问题陈述

我认为标题说明了一切:我正在寻找解析包含multipart / form-data HTTP请求的正文部分的 String 的方法。即字符串的内容看起来像这样:

--xyzseparator-blah
Content-Disposition: form-data; name="param1"

hello, world
--xyzseparator-blah
Content-Disposition: form-data; name="param2"

42
--xyzseparator-blah
Content-Disposition: form-data; name="param3"

blah, blah, blah
--xyzseparator-blah--

我希望获得的是parameters地图,或者类似的地图,就像这样。

parameters.get("param1");    // returns "hello, world"
parameters.get("param2");    // returns "42"
parameters.get("param3");    // returns "blah, blah, blah"
parameters.keys();           // returns ["param1", "param2", "param3"]

进一步的标准

  • 最好不要提供分隔符(在这种情况下是xyzseparator-blah),但如果我必须的话,我可以忍受它。
  • 我正在寻找一个基于库的解决方案,可能来自主流库(例如" Apache Commons"或类似的东西)。
  • 我想避免使用我自己的解决方案,但在目前阶段,我恐怕不得不这样做。原因:虽然通过一些字符串操作分割/解析上面的例子似乎微不足道,但真正的多部分请求体可以有更多的标题。除此之外,我不想重新发明(并且更少重新测试!)轮子:)

替代解决方案

如果有一个满足上述标准的解决方案,但其输入是Apache HttpRequest,而不是String,那也是可以接受的。 (基本上我确实收到HttpRequest,但我使用的内部库是这样构建的,它将此请求的主体作为String提取,并将其传递给负责执行此操作的类。但是,如果需要,我也可以直接在HttpRequest上工作。)

相关问题

无论我如何尝试通过Google,在SO和其他论坛上找到答案,解决方案似乎总是使用commons fileupload来完成各个部分。例如:hereherehereherehere ... 但是,在该解决方案中使用的parseRequest方法需要RequestContext,我没有(仅HttpRequest)。

在上面的一些答案中也提到的另一种方法是从HttpServletRequest获取参数(但同样,我只有HttpRequest)。

编辑:换句话说:我可以包括Commons Fileupload(我可以访问它),但这对我没有帮助,因为我有一个{{1并且Commons Fileupload需要HttpRequest。 (除非有一种简单的方法可以从RequestContext转换为HttpRequest,我忽略了这一点。)

1 个答案:

答案 0 :(得分:3)

您可以使用Commons FileUpload解析您的String,方法是将其包装在实现' org.apache.commons.fileupload.UploadContext'的类中,如下所示。

我建议将HttpRequest包装在您建议的备用解决方案中,但原因有两个。首先,使用String意味着整个多部分POST主体(包括文件内容)需要适合内存。包装HttpRequest将允许您流式传输,一次只有一个小内存缓冲区。其次,如果没有HttpRequest,你需要嗅出多部分边界,这通常是在“内容类型”中。标题(请参阅RFC1867)。

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

public class MultiPartStringParser implements org.apache.commons.fileupload.UploadContext {

    public static void main(String[] args) throws Exception {
        String s = new String(Files.readAllBytes(Paths.get(args[0])));
        MultiPartStringParser p = new MultiPartStringParser(s);
        for (String key : p.parameters.keySet()) {
            System.out.println(key + "=" + p.parameters.get(key));
        }
    }

    private String postBody;
    private String boundary;
    private Map<String, String> parameters = new HashMap<String, String>();

    public MultiPartStringParser(String postBody) throws Exception {
        this.postBody = postBody;
        // Sniff out the multpart boundary.
        this.boundary = postBody.substring(2, postBody.indexOf('\n')).trim();
        // Parse out the parameters.
        final FileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        List<FileItem> fileItems = upload.parseRequest(this);
        for (FileItem fileItem: fileItems) {
            if (fileItem.isFormField()){
                parameters.put(fileItem.getFieldName(), fileItem.getString());
            } // else it is an uploaded file
        }
    }

    public Map<String,String> getParameters() {
        return parameters;
    }

    // The methods below here are to implement the UploadContext interface.
    @Override
    public String getCharacterEncoding() {
        return "UTF-8"; // You should know the actual encoding.
    }

    // This is the deprecated method from RequestContext that unnecessarily
    // limits the length of the content to ~2GB by returning an int. 
    @Override
    public int getContentLength() {
        return -1; // Don't use this
    }

    @Override
    public String getContentType() {
        // Use the boundary that was sniffed out above.
        return "multipart/form-data, boundary=" + this.boundary;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(postBody.getBytes());
    }

    @Override
    public long contentLength() {
        return postBody.length();
    }
}
相关问题