緊接上一節(jié),本節(jié)記錄 【下載师痕,以流的方式獲取響應信息】
HttpClient
可以讓我們模擬瀏覽器進行訪問各個網站,同時也具備訪問網絡上的某個資源荐虐,對其進行下載的功能七兜。我們只需要把響應的信息以流的方式給保存到本地即可。
上代碼:
@Test
public void getUriResource() {
String imgUrl = "https://ws3.sinaimg.cn/large/9150e4e5ly1fhnc60l3cdj204r04qaa4.jpg";
// 獲取連接客戶端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
// 創(chuàng)建POST請求對象
HttpPost httpPost = new HttpPost(imgUrl);
/*
* 添加請求參數
*/
// 創(chuàng)建請求參數
List<NameValuePair> list = new LinkedList<>();
BasicNameValuePair param1 = new BasicNameValuePair("name", "root");
BasicNameValuePair param2 = new BasicNameValuePair("password", "123456");
list.add(param1);
list.add(param2);
// 使用URL實體轉換工具
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list);
httpPost.setEntity(entityParam);
/*
* 添加請求頭信息
*/
// 瀏覽器表示
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
// 傳輸的類型
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 執(zhí)行請求
response = httpClient.execute(httpPost);
// 獲得響應的實體對象
HttpEntity entity = response.getEntity();
/*
* 獲取到響應信息的流
*/
InputStream is = entity.getContent();
// 包裝成高效流
BufferedInputStream bis = new BufferedInputStream(is);
// 寫入本地 D 盤
File file = new File("D:/圖.jpg");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] byt = new byte[1024 * 8];
Integer len = -1;
while ((len = bis.read(byt)) != -1) {
bos.write(byt, 0, len);
}
bos.close();
bis.close();
} catch (ClientProtocolException e) {
System.err.println("Http協(xié)議出現問題");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("解析錯誤");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IO異常");
e.printStackTrace();
} finally {
// 釋放連接
if (null != response) {
try {
response.close();
httpClient.close();
} catch (IOException e) {
System.err.println("釋放連接出錯");
e.printStackTrace();
}
}
}
}
- 獲取到的圖片:
本節(jié)完畢福扬,下一節(jié)記錄【連接超時的配置】