如何經過訪問某一個網頁上的一個下載連接下載文件到本地呢?我學習了一下,利用httpget1,httpResponse1來判斷網絡是否鏈接訪問成功,又經過httpget2,httpResponse2來訪問下載連接實現文件下載。java
注意:在使用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); }