Java:使用HttpClient进行POST和GET请求以及文件上传和下载

来源:互联网 发布:方太云魔方的缺点知乎 编辑:程序博客网 时间:2024/05/22 05:30

1.HttpClient

大家可以先看一下HttpClient的介绍,这篇博文写的还算不错:http://blog.csdn.net/wangpeng047/article/details/19624529

当然,详细的文档,你可以去官方网站查看和下载:http://hc.apache.org/httpclient-3.x/

2.本博客简单介绍一下POST和GET以及文件下载的应用。

代码如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package net.mobctrl;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11. import java.util.Set;  
  12. import java.util.concurrent.ExecutorService;  
  13. import java.util.concurrent.Executors;  
  14.   
  15. import org.apache.http.HttpEntity;  
  16. import org.apache.http.NameValuePair;  
  17. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  18. import org.apache.http.client.methods.CloseableHttpResponse;  
  19. import org.apache.http.client.methods.HttpGet;  
  20. import org.apache.http.client.methods.HttpPost;  
  21. import org.apache.http.entity.ContentType;  
  22. import org.apache.http.entity.mime.MultipartEntityBuilder;  
  23. import org.apache.http.entity.mime.content.FileBody;  
  24. import org.apache.http.entity.mime.content.StringBody;  
  25. import org.apache.http.impl.client.CloseableHttpClient;  
  26. import org.apache.http.impl.client.HttpClients;  
  27. import org.apache.http.message.BasicNameValuePair;  
  28. import org.apache.http.util.EntityUtils;  
  29.   
  30. /** 
  31.  * @web http://www.mobctrl.net 
  32.  * @author Zheng Haibo 
  33.  * @Description: 文件下载 POST GET 
  34.  */  
  35. public class HttpClientUtils {  
  36.   
  37.     /** 
  38.      * 最大线程池 
  39.      */  
  40.     public static final int THREAD_POOL_SIZE = 5;  
  41.   
  42.     public interface HttpClientDownLoadProgress {  
  43.         public void onProgress(int progress);  
  44.     }  
  45.   
  46.     private static HttpClientUtils httpClientDownload;  
  47.   
  48.     private ExecutorService downloadExcutorService;  
  49.   
  50.     private HttpClientUtils() {  
  51.         downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);  
  52.     }  
  53.   
  54.     public static HttpClientUtils getInstance() {  
  55.         if (httpClientDownload == null) {  
  56.             httpClientDownload = new HttpClientUtils();  
  57.         }  
  58.         return httpClientDownload;  
  59.     }  
  60.   
  61.     /** 
  62.      * 下载文件 
  63.      *  
  64.      * @param url 
  65.      * @param filePath 
  66.      */  
  67.     public void download(final String url, final String filePath) {  
  68.         downloadExcutorService.execute(new Runnable() {  
  69.   
  70.             @Override  
  71.             public void run() {  
  72.                 httpDownloadFile(url, filePath, nullnull);  
  73.             }  
  74.         });  
  75.     }  
  76.   
  77.     /** 
  78.      * 下载文件 
  79.      *  
  80.      * @param url 
  81.      * @param filePath 
  82.      * @param progress 
  83.      *            进度回调 
  84.      */  
  85.     public void download(final String url, final String filePath,  
  86.             final HttpClientDownLoadProgress progress) {  
  87.         downloadExcutorService.execute(new Runnable() {  
  88.   
  89.             @Override  
  90.             public void run() {  
  91.                 httpDownloadFile(url, filePath, progress, null);  
  92.             }  
  93.         });  
  94.     }  
  95.   
  96.     /** 
  97.      * 下载文件 
  98.      *  
  99.      * @param url 
  100.      * @param filePath 
  101.      */  
  102.     private void httpDownloadFile(String url, String filePath,  
  103.             HttpClientDownLoadProgress progress, Map<String, String> headMap) {  
  104.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  105.         try {  
  106.             HttpGet httpGet = new HttpGet(url);  
  107.             setGetHead(httpGet, headMap);  
  108.             CloseableHttpResponse response1 = httpclient.execute(httpGet);  
  109.             try {  
  110.                 System.out.println(response1.getStatusLine());  
  111.                 HttpEntity httpEntity = response1.getEntity();  
  112.                 long contentLength = httpEntity.getContentLength();  
  113.                 InputStream is = httpEntity.getContent();  
  114.                 // 根据InputStream 下载文件  
  115.                 ByteArrayOutputStream output = new ByteArrayOutputStream();  
  116.                 byte[] buffer = new byte[4096];  
  117.                 int r = 0;  
  118.                 long totalRead = 0;  
  119.                 while ((r = is.read(buffer)) > 0) {  
  120.                     output.write(buffer, 0, r);  
  121.                     totalRead += r;  
  122.                     if (progress != null) {// 回调进度  
  123.                         progress.onProgress((int) (totalRead * 100 / contentLength));  
  124.                     }  
  125.                 }  
  126.                 FileOutputStream fos = new FileOutputStream(filePath);  
  127.                 output.writeTo(fos);  
  128.                 output.flush();  
  129.                 output.close();  
  130.                 fos.close();  
  131.                 EntityUtils.consume(httpEntity);  
  132.             } finally {  
  133.                 response1.close();  
  134.             }  
  135.         } catch (Exception e) {  
  136.             e.printStackTrace();  
  137.         } finally {  
  138.             try {  
  139.                 httpclient.close();  
  140.             } catch (IOException e) {  
  141.                 e.printStackTrace();  
  142.             }  
  143.         }  
  144.     }  
  145.   
  146.     /** 
  147.      * get请求 
  148.      *  
  149.      * @param url 
  150.      * @return 
  151.      */  
  152.     public String httpGet(String url) {  
  153.         return httpGet(url, null);  
  154.     }  
  155.   
  156.     /** 
  157.      * http get请求 
  158.      *  
  159.      * @param url 
  160.      * @return 
  161.      */  
  162.     public String httpGet(String url, Map<String, String> headMap) {  
  163.         String responseContent = null;  
  164.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  165.         try {  
  166.             HttpGet httpGet = new HttpGet(url);  
  167.             CloseableHttpResponse response1 = httpclient.execute(httpGet);  
  168.             setGetHead(httpGet, headMap);  
  169.             try {  
  170.                 System.out.println(response1.getStatusLine());  
  171.                 HttpEntity entity = response1.getEntity();  
  172.                 responseContent = getRespString(entity);  
  173.                 System.out.println("debug:" + responseContent);  
  174.                 EntityUtils.consume(entity);  
  175.             } finally {  
  176.                 response1.close();  
  177.             }  
  178.         } catch (Exception e) {  
  179.             e.printStackTrace();  
  180.         } finally {  
  181.             try {  
  182.                 httpclient.close();  
  183.             } catch (IOException e) {  
  184.                 e.printStackTrace();  
  185.             }  
  186.         }  
  187.         return responseContent;  
  188.     }  
  189.   
  190.     public String httpPost(String url, Map<String, String> paramsMap) {  
  191.         return httpPost(url, paramsMap, null);  
  192.     }  
  193.   
  194.     /** 
  195.      * http的post请求 
  196.      *  
  197.      * @param url 
  198.      * @param paramsMap 
  199.      * @return 
  200.      */  
  201.     public String httpPost(String url, Map<String, String> paramsMap,  
  202.             Map<String, String> headMap) {  
  203.         String responseContent = null;  
  204.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  205.         try {  
  206.             HttpPost httpPost = new HttpPost(url);  
  207.             setPostHead(httpPost, headMap);  
  208.             setPostParams(httpPost, paramsMap);  
  209.             CloseableHttpResponse response = httpclient.execute(httpPost);  
  210.             try {  
  211.                 System.out.println(response.getStatusLine());  
  212.                 HttpEntity entity = response.getEntity();  
  213.                 responseContent = getRespString(entity);  
  214.                 EntityUtils.consume(entity);  
  215.             } finally {  
  216.                 response.close();  
  217.             }  
  218.         } catch (Exception e) {  
  219.             e.printStackTrace();  
  220.         } finally {  
  221.             try {  
  222.                 httpclient.close();  
  223.             } catch (IOException e) {  
  224.                 e.printStackTrace();  
  225.             }  
  226.         }  
  227.         System.out.println("responseContent = " + responseContent);  
  228.         return responseContent;  
  229.     }  
  230.   
  231.     /** 
  232.      * 设置POST的参数 
  233.      *  
  234.      * @param httpPost 
  235.      * @param paramsMap 
  236.      * @throws Exception 
  237.      */  
  238.     private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)  
  239.             throws Exception {  
  240.         if (paramsMap != null && paramsMap.size() > 0) {  
  241.             List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
  242.             Set<String> keySet = paramsMap.keySet();  
  243.             for (String key : keySet) {  
  244.                 nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));  
  245.             }  
  246.             httpPost.setEntity(new UrlEncodedFormEntity(nvps));  
  247.         }  
  248.     }  
  249.   
  250.     /** 
  251.      * 设置http的HEAD 
  252.      *  
  253.      * @param httpPost 
  254.      * @param headMap 
  255.      */  
  256.     private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {  
  257.         if (headMap != null && headMap.size() > 0) {  
  258.             Set<String> keySet = headMap.keySet();  
  259.             for (String key : keySet) {  
  260.                 httpPost.addHeader(key, headMap.get(key));  
  261.             }  
  262.         }  
  263.     }  
  264.   
  265.     /** 
  266.      * 设置http的HEAD 
  267.      *  
  268.      * @param httpGet 
  269.      * @param headMap 
  270.      */  
  271.     private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {  
  272.         if (headMap != null && headMap.size() > 0) {  
  273.             Set<String> keySet = headMap.keySet();  
  274.             for (String key : keySet) {  
  275.                 httpGet.addHeader(key, headMap.get(key));  
  276.             }  
  277.         }  
  278.     }  
  279.   
  280.     /** 
  281.      * 上传文件 
  282.      *  
  283.      * @param serverUrl 
  284.      *            服务器地址 
  285.      * @param localFilePath 
  286.      *            本地文件路径 
  287.      * @param serverFieldName 
  288.      * @param params 
  289.      * @return 
  290.      * @throws Exception 
  291.      */  
  292.     public String uploadFileImpl(String serverUrl, String localFilePath,  
  293.             String serverFieldName, Map<String, String> params)  
  294.             throws Exception {  
  295.         String respStr = null;  
  296.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  297.         try {  
  298.             HttpPost httppost = new HttpPost(serverUrl);  
  299.             FileBody binFileBody = new FileBody(new File(localFilePath));  
  300.   
  301.             MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder  
  302.                     .create();  
  303.             // add the file params  
  304.             multipartEntityBuilder.addPart(serverFieldName, binFileBody);  
  305.             // 设置上传的其他参数  
  306.             setUploadParams(multipartEntityBuilder, params);  
  307.   
  308.             HttpEntity reqEntity = multipartEntityBuilder.build();  
  309.             httppost.setEntity(reqEntity);  
  310.   
  311.             CloseableHttpResponse response = httpclient.execute(httppost);  
  312.             try {  
  313.                 System.out.println(response.getStatusLine());  
  314.                 HttpEntity resEntity = response.getEntity();  
  315.                 respStr = getRespString(resEntity);  
  316.                 EntityUtils.consume(resEntity);  
  317.             } finally {  
  318.                 response.close();  
  319.             }  
  320.         } finally {  
  321.             httpclient.close();  
  322.         }  
  323.         System.out.println("resp=" + respStr);  
  324.         return respStr;  
  325.     }  
  326.   
  327.     /** 
  328.      * 设置上传文件时所附带的其他参数 
  329.      *  
  330.      * @param multipartEntityBuilder 
  331.      * @param params 
  332.      */  
  333.     private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,  
  334.             Map<String, String> params) {  
  335.         if (params != null && params.size() > 0) {  
  336.             Set<String> keys = params.keySet();  
  337.             for (String key : keys) {  
  338.                 multipartEntityBuilder  
  339.                         .addPart(key, new StringBody(params.get(key),  
  340.                                 ContentType.TEXT_PLAIN));  
  341.             }  
  342.         }  
  343.     }  
  344.   
  345.     /** 
  346.      * 将返回结果转化为String 
  347.      *  
  348.      * @param entity 
  349.      * @return 
  350.      * @throws Exception 
  351.      */  
  352.     private String getRespString(HttpEntity entity) throws Exception {  
  353.         if (entity == null) {  
  354.             return null;  
  355.         }  
  356.         InputStream is = entity.getContent();  
  357.         StringBuffer strBuf = new StringBuffer();  
  358.         byte[] buffer = new byte[4096];  
  359.         int r = 0;  
  360.         while ((r = is.read(buffer)) > 0) {  
  361.             strBuf.append(new String(buffer, 0, r, "UTF-8"));  
  362.         }  
  363.         return strBuf.toString();  
  364.     }  
  365. }  

我们可以使用如下代码进行测试:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.util.HashMap;  
  2. import java.util.LinkedHashMap;  
  3. import java.util.Map;  
  4.   
  5. import net.mobctrl.HttpClientUtils;  
  6. import net.mobctrl.HttpClientUtils.HttpClientDownLoadProgress;  
  7.   
  8. /** 
  9.  * @date 2015年1月14日 下午1:49:50 
  10.  * @author Zheng Haibo 
  11.  * @Description: 测试 
  12.  */  
  13. public class Main {  
  14.   
  15.     public static void main(String[] args) {  
  16.         /** 
  17.          * 测试下载文件 异步下载 
  18.          */  
  19.         HttpClientUtils.getInstance().download(  
  20.                 "http://newbbs.qiniudn.com/phone.png""test.png",  
  21.                 new HttpClientDownLoadProgress() {  
  22.   
  23.                     @Override  
  24.                     public void onProgress(int progress) {  
  25.                         System.out.println("download progress = " + progress);  
  26.                     }  
  27.                 });  
  28.   
  29.         // POST 同步方法  
  30.         Map<String, String> params = new HashMap<String, String>();  
  31.         params.put("username""admin");  
  32.         params.put("password""admin");  
  33.         HttpClientUtils.getInstance().httpPost(  
  34.                 "http://192.168.31.183:8080/SSHMySql/register", params);  
  35.   
  36.         // GET 同步方法  
  37.         HttpClientUtils.getInstance().httpGet(  
  38.                 "http://wthrcdn.etouch.cn/weather_mini?city=北京");  
  39.   
  40.         // 上传文件 POST 同步方法  
  41.         try {  
  42.             Map<String,String> uploadParams = new LinkedHashMap<String, String>();  
  43.             uploadParams.put("userImageContentType""image");  
  44.             uploadParams.put("userImageFileName""testaa.png");  
  45.             HttpClientUtils.getInstance().uploadFileImpl(  
  46.                     "http://192.168.31.183:8080/SSHMySql/upload""android_bug_1.png",  
  47.                     "userImage", uploadParams);  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         }  
  51.   
  52.     }  
  53.   
  54. }  




运行结果为:

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. HTTP/1.1 200 OK  
  2. responseContent = {"id":"-2","msg":"添加失败!用户名已经存在!"}  
  3. HTTP/1.1 200 OK  
  4. download progress = 6  
  5. download progress = 11  
  6. download progress = 13  
  7. download progress = 20  
  8. download progress = 22  
  9. download progress = 26  
  10. download progress = 31  
  11. download progress = 33  
  12. download progress = 35  
  13. download progress = 38  
  14. download progress = 40  
  15. download progress = 42  
  16. download progress = 44  
  17. download progress = 49  
  18. download progress = 53  
  19. download progress = 55  
  20. download progress = 57  
  21. download progress = 60  
  22. download progress = 62  
  23. download progress = 64  
  24. download progress = 66  
  25. download progress = 71  
  26. download progress = 77  
  27. download progress = 77  
  28. download progress = 80  
  29. download progress = 82  
  30. HTTP/1.1 200 OK  
  31. debug:{"desc":"OK","status":1000,"data":{"wendu":"3","ganmao":"昼夜温差很大,易发生感冒,请注意适当增减衣服,加强自我防护避免感冒。","forecast":[{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 6℃","type":"晴","low":"低温 -6℃","date":"22日星期四"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 6℃","type":"多云","low":"低温 -3℃","date":"23日星期五"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 5℃","type":"多云","low":"低温 -3℃","date":"24日星期六"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 5℃","type":"阴","low":"低温 -2℃","date":"25日星期天"},{"fengxiang":"无持续风向","fengli":"微风级","high":"高温 4℃","type":"多云","low":"低温 -2℃","date":"26日星期一"}],"yesterday":{"fl":"3-4级","fx":"北风","high":"高温 5℃","type":"晴","low":"低温 -6℃","date":"21日星期三"},"aqi":"124","city":"北京"}}  
  32. download progress = 84  
  33. download progress = 86  
  34. download progress = 88  
  35. download progress = 91  
  36. download progress = 93  
  37. download progress = 95  
  38. download progress = 99  
  39. download progress = 100  
  40. HTTP/1.1 200 OK  
  41. resp={"error_code":2000,"msg":"OK","filepath":"uploadfiles/192.168.31.72_android_bug_1.png"}  

下载过程有进度回调。

相关的libs包,可以在如下链接中下载:http://download.csdn.net/detail/nuptboyzhb/8362801

上述代码,既可以在J2SE,J2EE中使用,也可以在Android中使用,在android中使用时,需要相关的权限。

另外,测试所使用的Web项目为:https://github.com/nuptboyzhb/SSHMySQLDemo


转自http://blog.csdn.net/nupt123456789/article/details/42721003/


0 0