如何通過訪問某一個網頁上的一個下載鏈接下載文件到本地呢?我學習了一下,利用httpget1,httpResponse1來判斷網絡是否連接訪問成功,又通過httpget2,httpResponse2來訪問下載鏈接實現文件下載。
注意:在使用httpget2之前需使用語句“ httpget1.abort();”將get1關閉,否則會報異常。
/* 下載文件 @param urlsrc 網頁地址 @param outPath 文件輸出路徑 */ @SuppressWarnings({ "resource" }) public static String DownLoadPages(String urlsrc, String outpath) throws UnknownHostException { // 輸入流 InputStream in = null; // 文件輸出流 FileOutputStream out = null; try{ HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams,5000); //設置連接超時為5秒 HttpClient client = new DefaultHttpClient(httpParams); // 生成一個http客戶端發送請求對象 HttpGet httpget1 = new HttpGet(urlsrc); //對查詢頁面get HttpResponse httpResponse1 = client.execute(httpget1); // 發送請求並等待響應 // 判斷網絡連接是否成功 System.out.println("狀態碼:"+httpResponse1.getStatusLine().getStatusCode()); if (httpResponse1.getStatusLine().getStatusCode() != 200) System.out.println("網絡錯誤異常!!!!"); else System.out.println("網絡連接成功!!!"); httpget1.abort(); //關閉get HttpGet httpget2 = new HttpGet("http://....../download? DownloadFileName=All=true"); //對下載鏈接get實現下載 HttpResponse httpResponse2 = client.execute(httpget2); HttpEntity entity = httpResponse2.getEntity(); // 獲取響應里面的內容 in = entity.getContent(); // 得到服務氣端發回的響應的內容(都在一個流里面) out = new FileOutputStream(new File(outpath)); byte[] b = new byte[1024]; int len = 0; while((len=in.read(b))!= -1){ out.write(b,0,len); } in.close(); out.close(); }catch(Exception e){ e.printStackTrace(); } } System.out.println("download, success!!"); } public static void main(String[] args) throws Exception { String urlsrc="http://......//"; //要訪問的鏈接 String outPath="//...//..."; //本地路徑 DownLoadPages(src,outpath); }