我目前使用以下方法将 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 编码参数(home
和 favoriteflavor
)。直接使用输入流也会稍微高效一些,因为不需要解析参数。
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/