Java: Use HttpClient for POST and GET requests and file download, httpclientpost

Source: Internet
Author: User

Java: Use HttpClient for POST and GET requests and file download, httpclientpost

1. HttpClient

You can take a look at the introduction of HttpClient, this blog is not bad: http://blog.csdn.net/wangpeng047/article/details/19624529

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

2. This blog briefly introduces POST, GET, and object 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. apa Che. 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 {/*** maximum thread pool */public static final int THREAD_POOL_SIZE = 5; public interface HttpClientDownLoadProgress {public void onProgress (int progress);} private static HttpClientUtils httpClientDownload; private ExecutorService downloadExcutorService; private HttpClientUtils () {downloadExcutorService = Ex Ecutors. 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) implements downloadexcutorservice.exe cute (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) unzip downloadexcutorservice.exe cute (new Runnable () {@ Overridepublic void run () {httpDownloadFile (url, filePath, progress, null );}});} /***** download file ** @ param url * @ param filePath */private void httpDownloa DFile (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.exe cute (httpGet); try {System. out. println (response1.getStatusLine (); HttpEntity httpEntity = response1.getEntity (); long conte NtLength = httpEntity. getContentLength (); InputStream is = httpEntity. getContent (); // download the 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 SS. 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 ** @ p Aram 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.exe cute (httpGet); setGetHead (httpG Et, 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) {strBuf. append (new String (buffer, 0, r, "UTF-8");} responseContent = strBuf. toString (); System. out. println ("debug:" + responseContent); EntityU Tils. 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> 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.exe cute (httpPost ); try {System. out. println (response. getStatusLine (); HttpEntity entity = res Ponse. getEntity (); InputStream is = entity. getContent (); StringBuffer strBuf = new StringBuffer (); byte [] buffer = new byte [4096]; int r = 0; while (r = is. read (buffer)> 0) {strBuf. 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 the POST parameter ** @ param httpPost * @ param paramsMap * @ throws Exception */private void setPostParams (HttpPost httpPost, Map <String, String> paramsMap) throws Exception {if (paramsMap! = Null & paramsMap. size ()> 0) {List <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 the http HEAD ** @ param httpPost * @ param headMap */private void setPostHead (HttpPost httpPost, map <String, String> 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> headMap) {if (headMap! = Null & headMap. size ()> 0) {Set <String> keySet = headMap. keySet (); for (String key: keySet) {httpGet. addHeader (key, headMap. get (key ));}}}}

We can use the following code for testing:

Import java. util. hashMap; import java. util. map; import net. mobctrl. httpClientUtils; import net. mobctrl. httpClientUtils. httpClientDownLoadProgress;/*** @ date 1:49:50 on January 1, January 14, 2015 * @ author Zheng Haibo * @ Description: test */public class Main {public static void main (String [] args) {/*** test asynchronous download of the downloaded file */HttpClientUtils. getInstance (). download ("http://newbbs.qiniudn.com/phone.png", "test.png", new HttpClient DownLoadProgress () {@ Overridepublic void onProgress (int progress) {System. out. println ("download progress =" + progress) ;}}); // Map <String, String> params = new HashMap <String, String> (); params. 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 running result is:

HTTP/1.1 200 OKresponseContent = {"id": "-2", "msg": "failed to add! The user name already exists! "} HTTP/1.1 200 OKdebug: {" desc ":" OK "," status ": 1000," data ": {" wendu ":"-1 ", "ganmao": "The weather turns cooler, the air humidity is high, and it is easy to catch a cold. If you are physically weak, please pay attention to proper protection. "," Forecast ": [{" fengxiang ":" No sustained wind direction "," fengli ":" Breeze level "," high ":" high temperature 2 ℃ ", "type": "Xiao Xue", "low": "low Temperature-5 ℃", "date": "Wednesday 14" },{ "fengxiang ": "No sustained wind direction", "fengli": "Breeze level", "high": "high temperature 3 ℃", "type": "Haze", "low ": "Low Temperature-3 ℃", "date": "Thursday 15" },{ "fengxiang": "beifeng", "fengli": "4-5", "high ": "High Temperature 5 ℃", "type": "clear", "low": "low Temperature-6 ℃", "date": "Friday 16 "}, {"fengxiang": "No sustained wind direction", "fengli": "Breeze level", "high": "high Temperature 4 ℃", "type": "multi cloud ", "low": "low Temperature-5 ℃", "date": "Saturday 17" },{ "fengxiang": "No sustained wind direction", "fengli ": "Breeze level", "high": "high Temperature 6 ℃", "type": "multi cloud", "low": "low Temperature-4 ℃", "date ": "Sunday 18"}], "yesterday": {"fl": "Breeze", "fx": "No sustained wind direction", "high ": "High Temperature 4℃", "type": "Haze", "low": "low Temperature-4℃", "date": "Tuesday 13"}, "aqi ": & quot; 309 & quot;, & quot; city & quot ": "Beijing"} HTTP/1.1 200 OKdownload progress = 2 download progress = 6 download progress = 8 download progress = 10 download progress = 12 download progress = 15 download progress = 17 download progress = 20 download progress = 22 download progress = 27 download progress = 29 download progress = 31 download progress = 33 download progress = 36 download progress = 38 download progress = 40 download progress = 45 download progress = 47 download progress = 49 download progress = 51 download progress = 54 download progress = 56 download progress = 58 download progress = 60 download progress = 62 download progress = 69 download progress = 75 download progress = 81 download progress = 87 download progress = 89 download progress = 91 download progress = 93 download progress = 96 download progress = 100

The download process has a progress callback.

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

The above code can be used in J2SE and J2EE, or in Android. Related permissions are required when used in android.


Not for commercial purposes without permission



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.