HttpClient工具下載html頁面
阿新 • • 發佈:2018-11-05
import java.io.IOException; import org.apache.http.HttpEntity; 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.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * HttpClient工具下載html * @author jun */ public class PageDownLoadUtil { public static String getPageContent(String url) { HttpClientBuilder builder = HttpClients.custom(); //CloseableHttpClient是HttpClient介面的抽象類 CloseableHttpClient client = builder.build(); HttpGet request = new HttpGet(url); String content = null; try { CloseableHttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); content = EntityUtils.toString(entity); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } public static void main(String[] args) { String content = PageDownLoadUtil.getPageContent("http://www.hnwznz.com"); System.out.print(content); } }