HttpClient 通过资源URL下载资源
生活随笔
收集整理的這篇文章主要介紹了
HttpClient 通过资源URL下载资源
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
HttpClient 通過資源URL下載資源
使用富文本編輯器寫文章什么的,從第三方拷貝過來的圖文,里面的資源內容都是第三方的,如果第三方刪除該資源,導致該文章也無法訪問,故需要把文章中的第三方資源通過http下載到本地服務器,永久保存。
用到了以下三種方法:
1、純IO寫文件
/*** 根據url下載文件,保存到filepath中* @param url* @param filepath* @return*/ public static void download(String url, String filepath) {try {HttpClient client = HttpClients.createDefault();HttpGet httpGet = new HttpGet(url);//設置請求/*** setConnectTimeout:設置連接超時時間,單位毫秒。** setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連接池的。** setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。*/RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(3000).build();httpGet.setConfig(requestConfig);HttpResponse response = client.execute(httpGet);HttpEntity entity = response.getEntity();InputStream is = entity.getContent();File file = new File("C:\\Users\\XXX\\Downloads\\io");FileOutputStream fileout = new FileOutputStream(file);/*** 根據實際運行效果 設置緩沖區大小*/byte[] buffer = new byte[cache];int ch = 0;while ((ch = is.read(buffer)) != -1) {fileout.write(buffer, 0, ch);}is.close();fileout.flush();fileout.close();} catch (Exception e) {e.printStackTrace();}}注:由于該資源是網頁使用,此處沒有考慮文件類型,無文件格式后綴的文件,瀏覽器已然可以正常解析
2、使用HttpEntity自帶工具
import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption;/*** 使用httpClient自帶的工具類* @param url*/ public static void downloadByWriteTo(String url){try {RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(3000).build();CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();CloseableHttpResponse response = client.execute(new HttpGet(new URL(url).toURI()));HttpEntity entity = response.getEntity();File file = new File("C:\\Users\\XXX\\Downloads\\WriteTo");entity.writeTo(new FileOutputStream(file));} catch (Exception e) {e.printStackTrace();} }3、使用nio工具類拷貝
public static void downloadByFilesCopy(String url){try {HttpClient client = HttpClients.createDefault();HttpResponse response = client.execute(new HttpGet(url));HttpEntity entity = response.getEntity();File file = new File("C:\\Users\\XXX\\Downloads\\FilesCopy");Files.copy(entity.getContent(),file.toPath(), StandardCopyOption.REPLACE_EXISTING);} catch (Exception e) {e.printStackTrace();} }以上操作均需要導入HttpClient 包
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version> </dependency>總結
以上是生活随笔為你收集整理的HttpClient 通过资源URL下载资源的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小游戏 资源下载解压
- 下一篇: (转载)VS2010/MFC编程入门之四