Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send a file to form post with java

I have used Java to post information to a form before, but I have never done it with a file. I am testing this process with an image and text file, but apparently I have to change the way that I am doing it. The current way I am doing it (shown below) does not work and I am not completely sure if I can still use HttpClient.

The params part only accepts type string. I have a form that I am uploading files to a server with. The site I use for our CMS doesnt allow a direct connection so I have to upload files automatically with a form.

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();
    }
}
like image 345
shinjuo Avatar asked Oct 06 '22 20:10

shinjuo


1 Answers

Use setRequestEntity method to directly send file.

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

For sending as form-data, use MultipartRequestEntity

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

Ref: https://stackoverflow.com/a/2092508/324900

like image 125
Reddy Avatar answered Oct 10 '22 03:10

Reddy