我以前用 Java 将信息发布到表单,但我从未用文件做过。我正在用图像和文本文件测试这个过程,但显然我必须改变我做这件事的方式。我目前使用的方法(如下所示)不起作用,我不完全确定我是否仍然可以使用 HttpClient。
参数部分只接受字符串类型。我有一个用于将文件上传到服务器的表单。我用于 CMS 的站点不允许直接连接,因此我必须使用表单自动上传文件。
public static void main(String[] args) throws IOException {
File testText = new File("C://xxx/test.txt");
File testPicture = new File("C://xxx/test.jpg");
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("xxxx");
postMethod.addParameter("test", testText);
try {
httpClient.executeMethod(postMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
使用setRequestEntity
方法直接发送文件。
FileRequestEntity fre = new FileRequestEntity(new File("C://xxx/test.txt"), "text/plain");
post.setRequestEntity(fre);
postMethod.setRequestEntity(fre);
要作为表单数据发送,请使用 MultipartRequestEntity
File f = new File("C://xxx/test.txt");
Part[] parts = {
new FilePart("test", f)
};
postMethod.setRequestEntity(
new MultipartRequestEntity(parts, postMethod.getParams())
);
关于java - 使用java发送文件以形成帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13559192/