0

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

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

但这是添加“有效负载”的请求参数,这样当我想在我的 doPost servlet 中接收值时,我会这样做:

request.getParameter("payload");

我猜这个参数“有效负载”在请求标头中?

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

... = request.getInputStream();

我怎样才能修改我的代码来做到这一点?(使用httpclient)

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

4

1 回答 1

1

HttpClient上的Apache 文档有一个请求中的流数据示例:

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 请求的正文中。例如,以下是一个标准的 HTTP POST 请求,带有两个 URL 编码参数 (home) favorite flavor。直接使用输入流也会稍微高效一些,因为不需要解析参数。

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
于 2012-04-22T22:13:42.157 回答