httpclient下載檔案

來源:互聯網
上載者:User

標籤:列印   exec   dex   read   連網   執行   try   group   index   

在pom.xml中引入httpclientjar包:

    <!--httpclient 連網的資料轉送 -->        <dependency>            <groupId>org.apache.httpcomponents</groupId>            <artifactId>httpclient</artifactId>            <version>4.5.2</version>        </dependency>        <dependency>            <groupId>org.apache.httpcomponents</groupId>            <artifactId>httpcore</artifactId>            <version>4.4.6</version>        </dependency>        <!-- dom4j用來讀取XML檔案的-->        <dependency>            <groupId>org.jvnet.hudson.dom4j</groupId>            <artifactId>dom4j</artifactId>            <version>1.6.1-hudson-3</version>        </dependency>

寫java類代碼:

    private void executeGetMethod(int pageIndex, int pageSize) {        // 1、建立HttpClient 對象        CloseableHttpClient client = HttpClients.createDefault();        // 2、建立一個Get請求        HttpGet httpGet = new HttpGet(                "http://wcf.open.cnblogs.com/blog/sitehome/paged/" + pageIndex+ "/" + pageSize);        CloseableHttpResponse response = null;        try {            // 3、執行操作,並且得到響應的 輸出資料流            response = client.execute(httpGet);            // 4、得到響應流             中的 資料對象            HttpEntity entity = response.getEntity();            // 5、列印出響應碼 200 , 404 ,500, 403(非必要)            System.out.println(response.getStatusLine().getStatusCode());            // 6、判斷entity是不是為null            if (entity != null) {                // 開始讀取xml的資料,使用dom4j                //readXML(entity.getContent());其中entity.getContent()得到的是一個輸入資料流,對檔案進行解讀            }        } catch (IOException e) {            e.printStackTrace();        } finally {            // 關閉響應流,關閉串連            try {                if (response != null) {                    response.close();                }                if (client != null) {                    client.close();                }            } catch (Exception e2) {                e2.printStackTrace();            }        }    }

 

httpclient下載檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.