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

shi*_*juo 5 java forms post httpclient http-post

我之前使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Red*_*ddy 4

使用setRequestEntity方法直接发送文件。

FileRequestEntity fre = new FileRequestEntity(new File("C://xxx/test.txt"), "text/plain");
post.setRequestEntity(fre);
postMethod.setRequestEntity(fre);
Run Code Online (Sandbox Code Playgroud)

要作为表单数据发送,请使用MultipartRequestEntity

File f = new File("C://xxx/test.txt");
Part[] parts = {
    new FilePart("test", f)
};
postMethod.setRequestEntity(
    new MultipartRequestEntity(parts, postMethod.getParams())
    );
Run Code Online (Sandbox Code Playgroud)

参考:/sf/answers/146475591/