HttpClient File Upload

Source: Internet
Author: User

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




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.