记录一次httpClient下载文件的坑
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                记录一次httpClient下载文件的坑
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                用httpClient模擬瀏覽器下載文件的代碼,網上是很多的,自己copy了一個就高興的用起來,下載了幾百個文件之后,MD發(fā)現(xiàn)所有下載的文件都是損壞的、根本打不開,這TM就尷尬了啊,用瀏覽器下載是沒問題的啊。
下面看一下當時用的代碼:
private static void down(String url, String path, int index) {CloseableHttpClient httpclient = HttpClients.createDefault();HttpGet httpGet = new HttpGet(url);// 這個地方根據(jù)瀏覽器里的內容復制過來httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");httpGet.setHeader("Connection", "keep-alive");httpGet.setHeader("Cookie", "XXXXX瀏覽器里的cookie復制過來就可以");httpGet.setHeader("Host", "XX.XX.XX");try {CloseableHttpResponse response = httpclient.execute(httpGet);HttpEntity httpEntity = response.getEntity();InputStream in = httpEntity.getContent();String fileName = getFileName(response);File file = new File(path + fileName);FileOutputStream fOut = new FileOutputStream(file);// IOUtils.copy(in,fOut);byte[] buffer = new byte[4*1024];while (in.read(buffer) != -1) {fOut.write(buffer);}fOut.flush();in.close();fOut.close();System.out.println(index+"=============ok================" + path + fileName);} catch (IOException e) {e.printStackTrace();}}坑就坑在這個地方:
while (in.read(buffer) != -1) {fOut.write(buffer); }httpClient傳輸過來的流不一定會每次把 byte[] buffer寫滿,這種寫法在本地復制文件的時候是可以的,但是網絡流上就會出大問題,也就是out.write()的起終點沒有顯示的指定而是默認取buffer.length,每次緩存基本上都是讀不滿的,所以導致寫入大量的空流到文件中。這也長了個教訓,以后在調用API的時候能顯示指定的就不要用默認值,你不知道會出什么問題。
正確的寫法是這樣的:
int n = 0; while ((n=in.read(buffer)) != -1) {fOut.write(buffer,0,n); }或者有工具類可以用 IOUtils.copy(in,out);這個方法里的實現(xiàn)是一樣的。
?
另外:獲取文件名的方法附上:
private static String getFileName(CloseableHttpResponse response) {String fileName = "";Header header = response.getFirstHeader("Content-disposition");//System.out.println(JSONObject.toJSONString(response));//System.out.println(JSONObject.toJSONString(header));if (header != null) {HeaderElement[] headerElements = header.getElements();NameValuePair nameValuePair = headerElements[0].getParameterByName("filename");fileName = nameValuePair.getValue();//System.out.println("============fileName==============" + fileName);//System.out.println(nameValuePair.getName());}return fileName;}?
總結
以上是生活随笔為你收集整理的记录一次httpClient下载文件的坑的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Android 权限清单大全
- 下一篇: 方维互动直播系统(美女、游戏、会议、在线
