zoukankan      html  css  js  c++  java
  • http文件上传/下载

      1 package unit;
      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.HashMap;
     10 import java.util.LinkedHashMap;
     11 import java.util.List;  
     12 import java.util.Map;  
     13 import java.util.Set;  
     14 import java.util.concurrent.ExecutorService;  
     15 import java.util.concurrent.Executors;  
     16   
     17 import org.apache.http.HttpEntity;  
     18 import org.apache.http.NameValuePair;  
     19 import org.apache.http.client.entity.UrlEncodedFormEntity;  
     20 import org.apache.http.client.methods.CloseableHttpResponse;  
     21 import org.apache.http.client.methods.HttpGet;  
     22 import org.apache.http.client.methods.HttpPost;  
     23 import org.apache.http.entity.ContentType;  
     24 import org.apache.http.entity.mime.MultipartEntityBuilder;  
     25 import org.apache.http.entity.mime.content.FileBody;  
     26 import org.apache.http.entity.mime.content.StringBody;  
     27 import org.apache.http.impl.client.CloseableHttpClient;  
     28 import org.apache.http.impl.client.HttpClients;  
     29 import org.apache.http.message.BasicNameValuePair;  
     30 import org.apache.http.util.EntityUtils;  
     31   
     32 /** 
     33  * @web http://www.mobctrl.net 
     34  * @Description: 文件下载 POST GET 
     35  */  
     36 public class HttpClientUtils {  
     37     public static void main(String[] args) {
     38          HttpClientUtils.getInstance().download("http://h30318.www3.hp.com/pub/softlib/software13/COL60943/al-146795-2/DJ1110_Full_WebPack_40.11.1124.exe", "D:/down/DJ1110_Full_WebPack_40.11.1124.exe", new HttpClientDownLoadProgress() {  
     39             @Override  
     40             public void onProgress(int progress) {  
     41                 System.out.println("download progress = " + progress+"%");  
     42             }  
     43         });  
     44          
     45     /*    // POST 同步方法  
     46         Map<String, String> params = new HashMap<String, String>();  
     47         params.put("username", "admin");  
     48         params.put("password", "admin");  
     49         HttpClientUtils.getInstance().httpPost(  
     50                 "http://h30318.www3.hp.com/pub/softlib/software13/COL60943/al-146795-2/DJ1110_Full_WebPack_40.11.1124.exe", params);  
     51   
     52         // GET 同步方法  
     53         HttpClientUtils.getInstance().httpGet(  
     54                 "http://wthrcdn.etouch.cn/weather_mini?city=北京");  
     55   
     56         // 上传文件 POST 同步方法  
     57         try {  
     58             Map<String,String> uploadParams = new LinkedHashMap<String, String>();  
     59             uploadParams.put("userImageContentType", "image");  
     60             uploadParams.put("userImageFileName", "testaa.png");  
     61             HttpClientUtils.getInstance().uploadFileImpl(  
     62                     "http://192.168.31.183:8080/SSHMySql/upload", "android_bug_1.png",  
     63                     "userImage", uploadParams);  
     64         } catch (Exception e) {  
     65             e.printStackTrace();  
     66         }*/  
     67         
     68     }
     69     
     70   
     71     /** 
     72      * 最大线程池 
     73      */  
     74     public static final int THREAD_POOL_SIZE = 5;  
     75   
     76     public interface HttpClientDownLoadProgress {  
     77         public void onProgress(int progress);  
     78     }  
     79   
     80     private static HttpClientUtils httpClientDownload;  
     81   
     82     private ExecutorService downloadExcutorService;  
     83   
     84     private HttpClientUtils() {  
     85         downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);  
     86     }  
     87   
     88     public static HttpClientUtils getInstance() {  
     89         if (httpClientDownload == null) {  
     90             httpClientDownload = new HttpClientUtils();  
     91         }  
     92         return httpClientDownload;  
     93     }  
     94   
     95     /** 
     96      * 下载文件 
     97      *  
     98      * @param url 
     99      * @param filePath 
    100      */  
    101     public void download(final String url, final String filePath) {  
    102         downloadExcutorService.execute(new Runnable() {  
    103             @Override  
    104             public void run() {  
    105                 httpDownloadFile(url, filePath, null, null);  
    106             }  
    107         });  
    108     }  
    109   
    110     /** 
    111      * 下载文件 
    112      *  
    113      * @param url 
    114      * @param filePath 
    115      * @param progress 
    116      *            进度回调 
    117      */  
    118     public void download(final String url, final String filePath, final HttpClientDownLoadProgress progress) {  
    119         downloadExcutorService.execute(new Runnable() {  
    120             @Override  
    121             public void run() {  
    122                 httpDownloadFile(url, filePath, progress, null);  
    123             }  
    124         });  
    125     }  
    126   
    127     /** 
    128      * 下载文件 
    129      * @param url 
    130      * @param filePath 
    131      */  
    132     private void httpDownloadFile(String url, String filePath,  
    133             HttpClientDownLoadProgress progress, Map<String, String> headMap) {  
    134         CloseableHttpClient httpclient = HttpClients.createDefault();  
    135         try {  
    136             HttpGet httpGet = new HttpGet(url);  
    137             setGetHead(httpGet, headMap);  
    138             CloseableHttpResponse response1 = httpclient.execute(httpGet);  
    139             try {  
    140                 System.out.println(response1.getStatusLine());  
    141                 HttpEntity httpEntity = response1.getEntity();  
    142                 long contentLength = httpEntity.getContentLength();  
    143                 InputStream is = httpEntity.getContent();  
    144                 // 根据InputStream 下载文件  
    145                 ByteArrayOutputStream output = new ByteArrayOutputStream();  
    146                 byte[] buffer = new byte[4096];  
    147                 int r = 0;  
    148                 long totalRead = 0;  
    149                 while ((r = is.read(buffer)) > 0) {  
    150                     output.write(buffer, 0, r);  
    151                     totalRead += r;  
    152                     if (progress != null) {// 回调进度  
    153                         progress.onProgress((int) (totalRead * 100 / contentLength));  
    154                     }  
    155                 }  
    156                 FileOutputStream fos = new FileOutputStream(filePath);  
    157                 output.writeTo(fos);  
    158                 output.flush();  
    159                 output.close();  
    160                 fos.close();  
    161                 EntityUtils.consume(httpEntity);  
    162             } finally {  
    163                 response1.close();  
    164             }  
    165         } catch (Exception e) {  
    166             e.printStackTrace();  
    167         } finally {  
    168             try {  
    169                 httpclient.close();  
    170             } catch (IOException e) {  
    171                 e.printStackTrace();  
    172             }  
    173         }  
    174     }  
    175   
    176     /** 
    177      * get请求 
    178      *  
    179      * @param url 
    180      * @return 
    181      */  
    182     public String httpGet(String url) {  
    183         return httpGet(url, null);  
    184     }  
    185   
    186     /** 
    187      * http get请求 
    188      *  
    189      * @param url 
    190      * @return 
    191      */  
    192     public String httpGet(String url, Map<String, String> headMap) {  
    193         String responseContent = null;  
    194         CloseableHttpClient httpclient = HttpClients.createDefault();  
    195         try {  
    196             HttpGet httpGet = new HttpGet(url);  
    197             CloseableHttpResponse response1 = httpclient.execute(httpGet);  
    198             setGetHead(httpGet, headMap);  
    199             try {  
    200                 System.out.println(response1.getStatusLine());  
    201                 HttpEntity entity = response1.getEntity();  
    202                 responseContent = getRespString(entity);  
    203                 System.out.println("debug:" + responseContent);  
    204                 EntityUtils.consume(entity);  
    205             } finally {  
    206                 response1.close();  
    207             }  
    208         } catch (Exception e) {  
    209             e.printStackTrace();  
    210         } finally {  
    211             try {  
    212                 httpclient.close();  
    213             } catch (IOException e) {  
    214                 e.printStackTrace();  
    215             }  
    216         }  
    217         return responseContent;  
    218     }  
    219   
    220     public String httpPost(String url, Map<String, String> paramsMap) {  
    221         return httpPost(url, paramsMap, null);  
    222     }  
    223   
    224     /** 
    225      * http的post请求 
    226      *  
    227      * @param url 
    228      * @param paramsMap 
    229      * @return 
    230      */  
    231     public String httpPost(String url, Map<String, String> paramsMap,  
    232             Map<String, String> headMap) {  
    233         String responseContent = null;  
    234         CloseableHttpClient httpclient = HttpClients.createDefault();  
    235         try {  
    236             HttpPost httpPost = new HttpPost(url);  
    237             setPostHead(httpPost, headMap);  
    238             setPostParams(httpPost, paramsMap);  
    239             CloseableHttpResponse response = httpclient.execute(httpPost);  
    240             try {  
    241                 System.out.println(response.getStatusLine());  
    242                 HttpEntity entity = response.getEntity();  
    243                 responseContent = getRespString(entity);  
    244                 EntityUtils.consume(entity);  
    245             } finally {  
    246                 response.close();  
    247             }  
    248         } catch (Exception e) {  
    249             e.printStackTrace();  
    250         } finally {  
    251             try {  
    252                 httpclient.close();  
    253             } catch (IOException e) {  
    254                 e.printStackTrace();  
    255             }  
    256         }  
    257         System.out.println("responseContent = " + responseContent);  
    258         return responseContent;  
    259     }  
    260   
    261     /** 
    262      * 设置POST的参数 
    263      *  
    264      * @param httpPost 
    265      * @param paramsMap 
    266      * @throws Exception 
    267      */  
    268     private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)  
    269             throws Exception {  
    270         if (paramsMap != null && paramsMap.size() > 0) {  
    271             List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
    272             Set<String> keySet = paramsMap.keySet();  
    273             for (String key : keySet) {  
    274                 nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));  
    275             }  
    276             httpPost.setEntity(new UrlEncodedFormEntity(nvps));  
    277         }  
    278     }  
    279   
    280     /** 
    281      * 设置http的HEAD 
    282      *  
    283      * @param httpPost 
    284      * @param headMap 
    285      */  
    286     private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {  
    287         if (headMap != null && headMap.size() > 0) {  
    288             Set<String> keySet = headMap.keySet();  
    289             for (String key : keySet) {  
    290                 httpPost.addHeader(key, headMap.get(key));  
    291             }  
    292         }  
    293     }  
    294   
    295     /** 
    296      * 设置http的HEAD 
    297      *  
    298      * @param httpGet 
    299      * @param headMap 
    300      */  
    301     private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {  
    302         if (headMap != null && headMap.size() > 0) {  
    303             Set<String> keySet = headMap.keySet();  
    304             for (String key : keySet) {  
    305                 httpGet.addHeader(key, headMap.get(key));  
    306             }  
    307         }  
    308     }  
    309   
    310     /** 
    311      * 上传文件 
    312      *  
    313      * @param serverUrl 
    314      *            服务器地址 
    315      * @param localFilePath 
    316      *            本地文件路径 
    317      * @param serverFieldName 
    318      * @param params 
    319      * @return 
    320      * @throws Exception 
    321      */  
    322     public String uploadFileImpl(String serverUrl, String localFilePath,  
    323             String serverFieldName, Map<String, String> params)  
    324             throws Exception {  
    325         String respStr = null;  
    326         CloseableHttpClient httpclient = HttpClients.createDefault();  
    327         try {  
    328             HttpPost httppost = new HttpPost(serverUrl);  
    329             FileBody binFileBody = new FileBody(new File(localFilePath));  
    330   
    331             MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder  
    332                     .create();  
    333             // add the file params  
    334             multipartEntityBuilder.addPart(serverFieldName, binFileBody);  
    335             // 设置上传的其他参数  
    336             setUploadParams(multipartEntityBuilder, params);  
    337   
    338             HttpEntity reqEntity = multipartEntityBuilder.build();  
    339             httppost.setEntity(reqEntity);  
    340   
    341             CloseableHttpResponse response = httpclient.execute(httppost);  
    342             try {  
    343                 System.out.println(response.getStatusLine());  
    344                 HttpEntity resEntity = response.getEntity();  
    345                 respStr = getRespString(resEntity);  
    346                 EntityUtils.consume(resEntity);  
    347             } finally {  
    348                 response.close();  
    349             }  
    350         } finally {  
    351             httpclient.close();  
    352         }  
    353         System.out.println("resp=" + respStr);  
    354         return respStr;  
    355     }  
    356   
    357     /** 
    358      * 设置上传文件时所附带的其他参数 
    359      *  
    360      * @param multipartEntityBuilder 
    361      * @param params 
    362      */  
    363     private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,  
    364             Map<String, String> params) {  
    365         if (params != null && params.size() > 0) {  
    366             Set<String> keys = params.keySet();  
    367             for (String key : keys) {  
    368                 multipartEntityBuilder  
    369                         .addPart(key, new StringBody(params.get(key),  
    370                                 ContentType.TEXT_PLAIN));  
    371             }  
    372         }  
    373     }  
    374   
    375     /** 
    376      * 将返回结果转化为String 
    377      *  
    378      * @param entity 
    379      * @return 
    380      * @throws Exception 
    381      */  
    382     private String getRespString(HttpEntity entity) throws Exception {  
    383         if (entity == null) {  
    384             return null;  
    385         }  
    386         InputStream is = entity.getContent();  
    387         StringBuffer strBuf = new StringBuffer();  
    388         byte[] buffer = new byte[4096];  
    389         int r = 0;  
    390         while ((r = is.read(buffer)) > 0) {  
    391             strBuf.append(new String(buffer, 0, r, "UTF-8"));  
    392         }  
    393         return strBuf.toString();  
    394     }  
    395 }  
  • 相关阅读:
    PAT顶级 1024 Currency Exchange Centers (35分)(最小生成树)
    Codeforces 1282B2 K for the Price of One (Hard Version)
    1023 Have Fun with Numbers (20)
    1005 Spell It Right (20)
    1092 To Buy or Not to Buy (20)
    1118 Birds in Forest (25)
    1130 Infix Expression (25)
    1085 Perfect Sequence (25)
    1109 Group Photo (25)
    1073 Scientific Notation (20)
  • 原文地址:https://www.cnblogs.com/redhat0019/p/8034204.html
Copyright © 2011-2022 走看看