標籤:列印 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下載檔案