我目前使用以下网址将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);
但这是添加&#34;有效载荷&#34;的请求参数。这样当我想在我的doPost servlet中接收值时,我会这样做:
request.getParameter("payload");
我猜这个参数&#34;有效载荷&#34;在请求标题中?
我想要做的是将此文件发送到请求正文中,因此在我的doPost中,我必须从流中获取数据,即:
... = request.getInputStream();
如何修改我的代码才能执行此操作? (使用httpclient)
另外,有人可以解释2在请求格式方面的差异吗?
答案 0 :(得分:1)
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请求的主体中。作为example,以下是具有两个URL编码参数(home
和favorite flavor
)的标准HTTP POST请求。直接使用输入流也会稍微提高效率,因为不需要解析参数。
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