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();
    }
}
                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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With