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 }  

 

转载于:https://www.cnblogs.com/redhat0019/p/8034204.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: C HTTP文件上传下载是通过使用HTTP协议进行文件传输的一种方法。它通常用于从一个计算机将文件上传到另一个计算机或从服务器下载文件。 在文件上传过程中,客户端通过HTTP POST请求将文件发送给服务器。服务器端接收到文件后,可以将其保存到指定的位置,并返回相应的信息给客户端,确认文件上传成功。 在文件下载过程中,客户端通过HTTP GET请求从服务器获取文件。服务器端根据请求的文件路径找到相应的文件,并将文件的内容返回给客户端进行下载文件上传下载通常需要用到HTTP的multipart/form-data请求格式,该格式可以将文件和其他表单数据一起发送到服务器。 在实际应用中,我们可以使用一些开源的库来简化文件上传下载的过程,例如Python中的requests库、Java中的Apache HttpClient、JavaScript中的axios等。这些库提供了一些便捷的方法和函数,可以帮助我们实现文件的上传下载功能。 除了使用HTTP协议外,还可以使用其他协议来进行文件上传下载,例如FTP(File Transfer Protocol)和SFTP(Secure File Transfer Protocol)等。每种协议都有其特定的优势和应用场景,我们可以根据具体需求来选择适合的协议进行文件传输。 ### 回答2: HTTP文件上传下载是指通过HTTP协议实现文件的传输和下载。在HTTP协议中,文件上传下载是通过HTTP的POST和GET请求方法进行的。 文件上传:通过HTTP的POST请求方法,将文件的内容和相关信息作为请求的主体部分发送到服务器。通常情况下,需要在请求头中指定Content-Type为multipart/form-data,以表明请求主体中包含了二进制的文件数据。文件上传可以使用表单的形式,通过<input type="file">元素进行选择,也可以使用编程语言提供的相关API进行实现。一般来说,文件上传需要在服务器端进行相应处理,将接收到的文件保存到指定位置。 文件下载:通过HTTP的GET请求方法,客户端向服务器请求一个文件。服务器端根据请求的URL定位到相应的文件,并将文件内容作为响应的主体返回给客户端。在响应头中,可以设置Content-Disposition字段来指定文件的名称和下载方式,例如Content-Disposition: attachment; filename="example.txt",表示以附件的方式下载名为example.txt的文件。客户端接收到响应后,可以将文件保存到本地位置。 总结来说,HTTP文件上传下载是通过POST和GET请求方法实现的。文件上传通过POST请求将文件及相关信息发送到服务器,而文件下载则是通过GET请求从服务器获取文件并返回给客户端。 ### 回答3: HTTP文件上传下载是指通过HTTP协议进行文件的上传下载操作。在Web开发中,常常需要用户上传文件或者提供文件供用户下载,这就需要利用HTTP协议来实现文件的传输。 在文件上传时,客户端通过HTTP POST请求将文件发送给服务器。在请求头中设置Content-Type为multipart/form-data,同时将文件作为请求体的一部分发送给服务器。服务器接收到文件后,可以进行一些处理,例如保存到指定的位置或者进行其他操作。 在文件下载时,客户端发送一个HTTP GET请求给服务器,服务器将文件以指定的格式和方式返回给客户端。客户端接收到服务器返回的文件后,可以选择直接保存到本地或者进行其他处理,例如显示在浏览器中或者进行进一步操作。 在HTTP文件上传下载中,需要注意以下几点: 1. 文件大小限制:由于文件可能较大,所以需要进行大小限制,避免影响服务器性能和用户体验。 2. 文件类型限制:对于上传的文件,需要进行类型限制,避免上传危险文件或者无法处理的文件。 3. 文件存储位置:服务器需要设定合适的存储位置,将上传的文件保存到指定目录中,同时需要管理文件的命名和存储结构。 4. 文件传输进度显示:在上传下载大文件时,可以实现文件传输进度的显示,增强用户体验。 5. 安全性考虑:对于上传的文件,需要进行安全性检查,避免上传恶意文件导致服务器的安全风险。 总之,HTTP文件上传下载是在Web开发中常见的功能,通过使用HTTP协议进行文件的传输,可以方便地实现用户上传下载文件的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值