5

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();
    }
}
Community
  • 1
  • 1
shinjuo
  • 20,498
  • 23
  • 73
  • 104
  • Why are you doing it this way, you could use file upload – Shamis Shukoor Nov 26 '12 at 05:40
  • Can you explain file upload a little more? Can I use that to post a file to a file upload field in a form? – shinjuo Nov 26 '12 at 05:48
  • Was typing up a long-winded answer, but then realized this question has been asked and answered before on SO. See here: http://stackoverflow.com/questions/2304663/apache-httpclient-making-multipart-form-post – Perception Nov 26 '12 at 05:51

1 Answers1

4

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

Community
  • 1
  • 1
Reddy
  • 8,737
  • 11
  • 55
  • 73
  • How do you choose which field gets that file attached to it when posted? When you use the params method you select what the field id was that the content belongs to – shinjuo Nov 26 '12 at 05:46
  • Updated my answer. Please check. – Reddy Nov 26 '12 at 06:00