Send file to create message with java

I used to use Java to submit information to a form, but I never did it with a file. I am testing this process with an image and a text file, but apparently I need to change the way I do it. The current way I do this (shown below) does not work, and I'm not quite sure if I can use HttpClient.

The params parameter accepts only a type string. I have a form with which I upload files to the server. The site that I use for our CMS does not allow a direct connection, so I have to automatically upload files using the 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(); } } 
+4
source share
1 answer

Use the setRequestEntity method to send the file directly.

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

To submit 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()) ); 

Link: fooobar.com/questions/162436 / ...

+4
source

All Articles