多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內(nèi)最全I(xiàn)T社區(qū)平臺 聯(lián)系我們 | 收藏本站
阿里云優(yōu)惠2
您當(dāng)前位置:首頁 > php開源 > php教程 > Java:使用HttpClient進(jìn)行POST和GET請求以及文件下載

Java:使用HttpClient進(jìn)行POST和GET請求以及文件下載

來源:程序員人生   發(fā)布時(shí)間:2015-03-06 08:43:48 閱讀次數(shù):2859次

1.HttpClient

大家可以先看1下HttpClient的介紹,這篇博文寫的還算不錯(cuò):http://blog.csdn.net/wangpeng047/article/details/19624529

固然,詳細(xì)的文檔,你可以去官方網(wǎng)站查看和下載:http://hc.apache.org/httpclient⑶.x/

2.本博客簡單介紹1下POST和GET和文件下載的利用。

代碼以下:

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: 文件下載 POST GET */ public class HttpClientUtils { /** * 最大線程池 */ 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 = Executors.newFixedThreadPool(THREAD_POOL_SIZE); } public static HttpClientUtils getInstance() { if (httpClientDownload == null) { httpClientDownload = new HttpClientUtils(); } return httpClientDownload; } /** * 下載文件 * * @param url * @param filePath */ public void download(final String url, final String filePath) { downloadExcutorService.execute(new Runnable() { @Override public void run() { httpDownloadFile(url, filePath, null,null); } }); } /** * 下載文件 * * @param url * @param filePath * @param progress * 進(jìn)度回調(diào) */ public void download(final String url, final String filePath, final HttpClientDownLoadProgress progress) { downloadExcutorService.execute(new Runnable() { @Override public void run() { httpDownloadFile(url, filePath, progress,null); } }); } /** * 下載文件 * * @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(); // 根據(jù)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) {// 回調(diào)進(jìn)度 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要求 * * @param url * @return */ public String httpGet(String url) { return httpGet(url, null); } /** * http get要求 * * @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) { strBuf.append(new String(buffer, 0, r, "UTF⑻")); } 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要求 * * @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.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) { strBuf.append(new String(buffer, 0, r, "UTF⑻")); } 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; } /** * 設(shè)置POST的參數(shù) * * @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)); } } /** * 設(shè)置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)); } } } /** * 設(shè)置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)); } } } }

我們可使用以下代碼進(jìn)行測試:

import java.util.HashMap; import java.util.Map; import net.mobctrl.HttpClientUtils; import net.mobctrl.HttpClientUtils.HttpClientDownLoadProgress; /** * @date 2015年1月14日 下午1:49:50 * @author Zheng Haibo * @Description: 測試 */ public class Main { public static void main(String[] args) { /** * 測試下載文件 異步下載 */ HttpClientUtils.getInstance().download( "http://newbbs.qiniudn.com/phone.png", "test.png", new HttpClientDownLoadProgress() { @Override public void onProgress(int progress) { System.out.println("download progress = " + progress); } }); // POST 同步方法 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 同步方法 HttpClientUtils.getInstance().httpGet( "http://wthrcdn.etouch.cn/weather_mini?city=北京"); } }

運(yùn)行結(jié)果為:

HTTP/1.1 200 OK responseContent = {"id":"⑵","msg":"添加失敗!用戶名已存在!"} HTTP/1.1 200 OK debug:{"desc":"OK","status":1000,"data":{"wendu":"⑴","ganmao":"天氣轉(zhuǎn)涼,空氣濕度較大,較易產(chǎn)生感冒,體質(zhì)較弱的朋友請注意適當(dāng)防護(hù)。","forecast":[{"fengxiang":"無延續(xù)風(fēng)向","fengli":"微風(fēng)級","high":"高溫 2℃","type":"小雪","low":"低溫 ⑸℃","date":"14日星期3"},{"fengxiang":"無延續(xù)風(fēng)向","fengli":"微風(fēng)級","high":"高溫 3℃","type":"霾","low":"低溫 ⑶℃","date":"15日星期4"},{"fengxiang":"北風(fēng)","fengli":"4⑸級","high":"高溫 5℃","type":"晴","low":"低溫 ⑹℃","date":"16日星期5"},{"fengxiang":"無延續(xù)風(fēng)向","fengli":"微風(fēng)級","high":"高溫 4℃","type":"多云","low":"低溫 ⑸℃","date":"17日星期6"},{"fengxiang":"無延續(xù)風(fēng)向","fengli":"微風(fēng)級","high":"高溫 6℃","type":"多云","low":"低溫 ⑷℃","date":"18日星期天"}],"yesterday":{"fl":"微風(fēng)","fx":"無延續(xù)風(fēng)向","high":"高溫 4℃","type":"霾","low":"低溫 ⑷℃","date":"13日星期2"},"aqi":"309","city":"北京"}} HTTP/1.1 200 OK download 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

下載進(jìn)程有進(jìn)度回調(diào)。

相干的libs包,可以在以下鏈接中下載:http://download.csdn.net/detail/nuptboyzhb/8362801

上述代碼,既可以在J2SE,J2EE中使用,也能夠在Android中使用,在android中使用時(shí),需要相干的權(quán)限。


未經(jīng)允許不得用于商業(yè)目的



生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關(guān)閉
程序員人生
主站蜘蛛池模板: 成人77777| 老司机亚洲精品影院在线 | 欧美一区中文字幕 | 毛片破处| japanese高清广州国产 | 亚洲国产欧美精品 | 最近中文字幕1视频 | 国产精品99久久久久久人 | 国产精品vs欧美精品 | 日韩欧美在线第一页 | 国产视频一区在线播放 | 亚洲日本视频在线观看 | 国产一级做a爱免费视频 | 精品剧情v国产在免费线观看 | 91精品国产亚一区二区三区 | 国产色综合久久无码有码 | 亚洲视频免费播放 | 国产亚洲精品一区二区久久 | 一二三四在线播放免费视频中国 | 日本一级毛片片在线播放 | 欧美色爽| 国产成人啪午夜精品网站男同 | 99精品国产一区二区三区 | 亚洲最新在线观看 | 伊人伊人 | 午夜在线观看视频在线播放版 | 宇都宫紫苑在线播放 | 鲁在线 | 亚洲护士 | 亚洲一级成人 | 一级爱爱片一级毛片-一毛 一级爱一级做a性视频 | a级片毛片 | 欧美一级在线免费观看 | 国内精品一区二区三区 | 国产成人精选视频69堂 | 亚洲色图日韩 | 欧美亚洲综合在线观看 | 午夜影院欧美 | 免费看h视频| 91九色最新地址 | 欧美jjzz|