用HtppClient下載一個網頁的完整代碼

lidki 9年前發布 | 1K 次閱讀 Java HtppClient

 import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class DownloadWebPage{

public static void downloadPagebyGetMethod() throws IOException {  

    // 1、通過HttpGet獲取到response對象  
    CloseableHttpClient httpClient = HttpClients.createDefault();  
    HttpGet httpGet = new HttpGet("http://www.baidu.com/");  
    CloseableHttpResponse response = httpClient.execute(httpGet);  

    InputStream is = null;  
    Scanner sc = null;  
    Writer os = null;  
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
        try {  
            // 2、獲取response的entity。  
            HttpEntity entity = response.getEntity();  

            // 3、獲取到InputStream對象,并對內容進行處理  
            is = entity.getContent();  
            sc = new Scanner(is);  
            // String filename = path.substring(path.lastIndexOf('/')+1);  
            String filename = "2.txt";  
            os = new PrintWriter(filename);  
            while (sc.hasNext()) {  
                os.write(sc.nextLine());  
            }  

        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } finally {  
            if (sc != null) {  
                sc.close();  
            }  
            if (is != null) {  
                is.close();  
            }  
            if (os != null) {  
                os.close();  
            }  
            if (response != null) {  
                response.close();  
            }  
        }  
    }  

}  

public static void main(String[] args) {  
    try {  
        downloadPagebyGetMethod();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}  

} </pre>

 本文由用戶 lidki 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!