Recent work needs to be crawled from the network to upload a lot of pictures on the server, file upload with the Apache httpclient 4.3, recorded for later lookup!
The code is as follows:
/** * Example How to use Multipart/form encoded POST request. */public class Clientmultipartformpost {public static void main (string[] args) throws Exception {if args.
Length!= 1) {System.out.println ("File Path not given");
System.exit (1);
} closeablehttpclient httpclient = Httpclients.createdefault (); try {httppost httppost = new HttpPost ("http://localhost:8080 +"/SERVLETS-EXAMPLES/SERVL
Et/requestinfoexample ");
Filebody img = new Filebody (new File (args[0));
Stringbody filename = new Stringbody ("A binary file of some kind", contenttype.text_plain);
Stringbody comment = new Stringbody ("A binary file of some kind", contenttype.text_plain); Httpentity reqentity = Multipartentitybuilder.create (). Addpart ("IMG", IMG). ADDPA RT ("filename", filename). Addpart ("comment", comment). Build ();
Httppost.setentity (reqentity);
SYSTEM.OUT.PRINTLN ("Executing request" + httppost.getrequestline ());
Closeablehttpresponse response = Httpclient.execute (HttpPost);
try {System.out.println ("----------------------------------------");
System.out.println (Response.getstatusline ());
Httpentity resentity = response.getentity (); if (resentity!= null) {System.out.println ("Response Content Length:" + resentity.getcontentlength ()
);
} entityutils.consume (resentity);
finally {response.close ();
finally {httpclient.close (); }
}
}
More usage of httpclient can be referenced in official documentation: https://hc.apache.org/httpcomponents-client-4.3.x/examples.html