Java: Use httpclient for post and get requests and file downloads

Source: Internet
Author: User

1.HttpClient

We can first look at the introduction of httpclient, this blog post is quite good: http://blog.csdn.net/wangpeng047/article/details/19624529

Of course, detailed documentation, you can go to the official website to view and download: http://hc.apache.org/httpclient-3.x/

2. This blog briefly describes the post and get and file download applications.

The code is as follows:

Package Net.mobctrl;import Java.io.bytearrayoutputstream;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.util.arraylist;import Java.util.List;import Java.util.map;import Java.util.set;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Org.apache.http.httpentity;import Org.apache.http.namevaluepair;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.CloseableHttpResponse; Import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.closeablehttpclient;import Org.apache.http.impl.client.httpclients;import Org.apache.http.message.basicnamevaluepair;import org.apache.http.util.entityutils;/** * @web/HTTP// Www.mobctrl.net * @author Zheng Haibo * @Description: File download POST GET */public class Httpclientutils {/** * max thread pool */public s tatic Final int thread_pool_size = 5;public interface Httpclientdownloadprogress {public void onprogress (int progress);} private static httpclientutils httpclientdownload;private Executorservice downloadexcutorservice;private Httpclientutils () {downloadexcutorservice = Executors.newfixedthreadpool (thread_pool_size);} public static Httpclientutils getinstance () {if (httpclientdownload = = null) {httpclientdownload = new httpclientutils (); }return Httpclientdownload;} /** * Download file * * @param URL * @param filePath */public void Download (final string url, final string filePath) {Downloadexcu Torservice.execute (New Runnable () {@Overridepublic void run () {httpdownloadfile (URL, FilePath, null,null);}});} /** * Download file * * @param URL * @param filePath * @param progress * Progress callback */public void download (Final String URL, Final String filepath,final httpclientdownloadprogress progress) {Downloadexcutorservice.execute (new Runnable () {@ overridepublic void Run () {httpdownloadfile (URL, FilePath, progress,null);}}); /** * Download file * * @param URL * @param filePath */private VOID httpdownloadfile (string URL, string filepath,httpclientdownloadprogress progress, map<string, string> Headmap) {Closeablehttpclient httpclient = Httpclients.createdefault (); try {httpget httpget = new HttpGet (URL); Setgethead (HttpGet, Headmap); Closeablehttpresponse response1 = Httpclient.execute (httpget); try {System.out.println (Response1.getstatusline ()); Httpentity httpentity = response1.getentity (); Long contentlength = Httpentity.getcontentlength (); InputStream is = Httpentity.getcontent ();//download file according to InputStream bytearrayoutputstream output = new Bytearrayoutputstream (); byte[] Buffer = new Byte[4096];int r = 0;long Totalread = 0;while ((r = is.read (buffer)) > 0) {output.write (buffer, 0, R); Totalread + = R;if (Progress! = NULL) {//Callback Progress Progress.onprogress ((int) (Totalread * 100/contentlength));}} FileOutputStream fos = new FileOutputStream (FilePath); Output.writeto (FOS); Output.flush (); Output.close (); Fos.close ( ); Entityutils.consume (httpentity);} finally {response1.close ();}} CatcH (Exception e) {e.printstacktrace ();} finally {try {httpclient.close ();} catch (IOException e) {e.printstacktrace ();}}} /** * GET request * * @param URL * @return */public string httpget (string url) {return httpget (URL, null);} /** * HTTP GET request * * @param URL * @return */public string httpget (string url, map<string, string> headmap) {string Responsecontent = null; Closeablehttpclient httpclient = Httpclients.createdefault (); try {httpget httpget = new HttpGet (URL); Closeablehttpresponse response1 = Httpclient.execute (HttpGet); Setgethead (HttpGet, headmap); try {System.out.println ( Response1.getstatusline ()); httpentity entity = response1.getentity (); InputStream is = Entity.getcontent (); StringBuffer strbuf = new StringBuffer () byte[] buffer = new Byte[4096];int r = 0;while ((r = is.read (buffer)) > 0) {St Rbuf.append (new String (buffer, 0, R, "UTF-8")); Responsecontent = Strbuf.tostring (); System.out.println ("debug:" + responsecontent); Entityutils.consume (entity);} finally {response1.close ();}} catch (Exception e) {e.printstacktrace ();} finally {try {httpclient.close ();} catch (IOException e) {e.printstacktrace ( );}} return responsecontent;} public string httppost (string url, map<string, string> paramsmap) {return HttpPost (URL, paramsmap, null);} /** * HTTP POST request * * @param URL * @param paramsmap * @return */public string httppost (string url, map<string, string& Gt Paramsmap,map<string, string> headmap) {String responsecontent = null; Closeablehttpclient httpclient = Httpclients.createdefault (); try {httppost httppost = new HttpPost (URL); Setposthead ( HttpPost, Headmap); Setpostparams (HttpPost, Paramsmap); Closeablehttpresponse response = Httpclient.execute (HttpPost); try {System.out.println (Response.getstatusline ()); httpentity entity = response.getentity (); InputStream is = Entity.getcontent (); StringBuffer strbuf = new StringBuffer () byte[] buffer = new Byte[4096];int r = 0;while ((r = is.read (buffer)) > 0) {St Rbuf.append (new String (buffer, 0, R, "UTF-8")); ResponsEContent = Strbuf.tostring (); Entityutils.consume (entity);} finally {response.close ();}} catch (Exception e) {e.printstacktrace ();} finally {try {httpclient.close ();} catch (IOException e) {e.printstacktrace () ;}} System.out.println ("responsecontent =" + responsecontent); return responsecontent;} /** * Set Post parameters * * @param httppost * @param paramsmap * @throws Exception */private void Setpostparams (HttpPost httppost , map<string, string> paramsmap) throws Exception {if (Paramsmap! = null && paramsmap.size () > 0) {list&lt ; namevaluepair> Nvps = new arraylist<namevaluepair> (); set<string> KeySet = Paramsmap.keyset (); for (String Key:keyset) {nvps.add (New Basicnamevaluepair (Key, Paramsmap.get (key)));} Httppost.setentity (New Urlencodedformentity (Nvps));}} /** * Set HTTP head * * @param httppost * @param headmap */private void Setposthead (HttpPost httppost, map<string, Strin G> headmap) {if (Headmap! = null && headmap.size () > 0) {set<string> keySet = Headmap.keyset (); for (String Key:keyset) {Httppost.addheader (key, Headmap.get (key));}}} /** * Set HTTP head * * @param httpget * @param headmap */private void Setgethead (HttpGet httpget, map<string, String&gt ; Headmap) {if (Headmap! = null && headmap.size () > 0) {set<string> keySet = Headmap.keyset (); for (String K Ey:keyset) {Httpget.addheader (key, Headmap.get (key));}}}}

We can test it with the following code:

Import Java.util.hashmap;import Java.util.map;import Net.mobctrl.httpclientutils;import net.mobctrl.httpclientutils.httpclientdownloadprogress;/** * @date January 14, 2015 PM 1:49:50 * @author Zheng Haibo * @ Description: Test */public class Main {public static void main (string[] args) {/** * Test download file asynchronous download */httpclientutils.getinstan CE (). Download ("Http://newbbs.qiniudn.com/phone.png", "Test.png", new Httpclientdownloadprogress () {@Overridepublic void OnProgress (int progress) {System.out.println ("Download progress =" + progress);}); /POST synchronization method map<string, string> params = new hashmap<string, string> ();p arams.put ("username", "admin"); Params.put ("Password", "admin"); Httpclientutils.getinstance (). HttpPost ("Http://localhost:8080/sshmysql/register", params);//GET Synchronization method Httpclientutils.getinstance (). HttpGet ("http://wthrcdn.etouch.cn/weather_mini?city= Beijing");}

The result of the operation is:

http/1.1 okresponsecontent = {"id": "2", "MSG": "Add failed!" user name already exists! "}http/1.1 okdebug:{" desc ":" OK "," status ": +," data ": {" Wendu ":" 1 "," Ganmao ":" The weather turns cool, the air humidity is bigger, the cold is easy to occur, The weaker of the friend please pay attention to appropriate protection. "," forecast ": [{" Fengxiang ":" No continuous Wind Direction "," Fengli ":" Breeze Level "," High ":" Hot 2 ℃ "," type ":" Snow "," Low ":" Cryogenic -5℃ "," date ":" 14th Wed "},{" Fengxiang ":" No continuous Wind Direction "," Fengli ":" Breeze Level "," High ":" Hot 3 ℃ "," type ":" Haze "," Low ":" Cryogenic -3℃ "," date ":" 15th Thursday "},{" Fengxiang ":" North Wind "," Fengli ":" 4-5 "," High ":" 5 ℃ "," type ":" Sunny "," Low ":" Cryogenic -6℃ "," date ":" 16th Friday "},{" Fengxiang ":" No continuous Wind Direction "," Fengli ":" Breeze "," High ":" 4 ℃ "," type ":" Cloudy "," Low ":" -5℃ "," date ":" 17th Saturday "},{" Fengxiang ":" No continuous Wind Direction "," Fengli ":" Breeze Level "," High ":" Hot 6 ℃ "," Type ":" Cloudy "," Low ":" Lo -4℃ "," date ":" 18th Sunday "}]," Yesterday ": {" fl ":" Breeze "," FX ":" No continuous Wind Direction "," High ":" Temperature 4 ℃ "," type ":" Haze "," lower ": "Low Temperature -4℃", "date": "13th Tuesday"}, "AQI": "309", "City": "Beijing"}}http/1.1 okdownload progress = 2download progress = 6download Progress = 8download Progress = 10download Progress = 12download Progress = 15download Progress = 17download progress = 20 Download progress = 22downloAd progress = 27download Progress = 29download Progress = 31download Progress = 33download progress = 36download Progress  = 38download Progress = 40download Progress = 45download Progress = 47download Progress = 49download progress = 51download Progress = 54download Progress = 56download Progress = 58download Progress = 60download Progress = 62download progress = 69download progress = 75download Progress = 81download Progress = 87download Progress = 89download progress = 91download P Rogress = 93download Progress = 96download progress = 100

The download process has a progress callback.

The relevant LIBS package can be downloaded in the following link: http://download.csdn.net/detail/nuptboyzhb/8362801

The above code, which can be used in J2SE,J2EE or Android, requires relevant permissions when used in Android.


Not permitted for commercial purposes without permission



Java: Use httpclient for post and get requests and file downloads

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.