使用java发送文件以形成帖子

前端之家收集整理的这篇文章主要介绍了使用java发送文件以形成帖子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我之前使用Java将信息发布到表单,但我从未使用过文件.我正在使用图像和文本文件测试此过程,但显然我必须改变我的方式.我正在做的当前方式(如下所示)不起作用,我不完全确定我是否仍然可以使用HttpClient.

params部分只接受类型字符串.我有一个表单,我将文件上传到服务器.我用于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())
    );

参考:https://stackoverflow.com/a/2092508/324900

原文链接:https://www.f2er.com/java/438251.html

猜你在找的Java相关文章