使用HTTP協議從網上擷取資源下載到本地(1)

來源:互聯網
上載者:User

建立工具類:

package com.blueZhang;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class Demo4 {// 擷取伺服器端資源的位元組輸入資料流public static InputStream getInputStream(String path) {//URL url;//try {url = new URL(path);//HttpURLConnection conn = (HttpURLConnection) url.openConnection();//conn.setRequestMethod("GET");//conn.setConnectTimeout(5000);//conn.setDoInput(true);//if (conn.getResponseCode() == 200) {//InputStream is = conn.getInputStream();return is;}} catch (Exception e) {e.printStackTrace();}return null;}// 讀取伺服器端的資源public static void writeToFile(InputStream input) {//FileOutputStream fos = null;//try {//fos = new FileOutputStream("file/1.txt");//byte[] arr = new byte[1024];//int len = 0;//while ((len = input.read(arr)) != -1) {//fos.write(arr, 0, len);//fos.flush();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {if (input != null) {try {input.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (fos != null) {try {fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}public static void main(String[] args) {}}
建立測試類別

package com.blueZhang;import java.io.InputStream;public class Test {/** * @param args */public static void main(String[] args) {String path = "http://news.xinhuanet.com/ttgg/2015-08/23/c_1116344298.htm";InputStream in = HttpUtils.getInputStream(path);HttpUtils.writeToFile(in);}}




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.