HttpClient--入門

BtWangZhi發表於2017-10-26

1 獲取網頁程式碼

public static void main(String[] args){
        CloseableHttpClient httpClient = HttpClients.createDefault();//建立httpclient例項
        HttpGet httpGet=new HttpGet("http://www.open1111.com");
        CloseableHttpResponse response=null;
        try {
             response= httpClient.execute(httpGet);
        } catch (ClientProtocolException e) {//協議異常
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity=response.getEntity();
        try {
            String string = EntityUtils.toString(entity,"utf-8");
            System.out.println(string);
        } catch (ParseException e) {//解析異常
            e.printStackTrace();
        } catch (IOException e) {//IO異常
            e.printStackTrace();
        }
        try {
            response.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2 獲取相關資訊
2.1 獲取返回的狀態資訊:

CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println("Status:"+response.getStatusLine().getStatusCode());

2.2 獲取返回頭資訊中ContentType的值

System.out.println(entity.getContentType().getValue());

摘自:http://www.open1111.com

3 獲取圖片

public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();// 建立httpclient例項
        HttpGet httpGet = new HttpGet("https://www.baidu.com/img/bd_logo1.png");
        //設定請求頭資訊User-Agent模擬瀏覽器
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/56.0");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if(entity!=null){
            System.out.println("ContentType:"+entity.getContentType().getValue());
            InputStream content = entity.getContent();
            //複製檔案到本地
            //org.codehaus.plexus.util.FileUtils.copyURLToFile(new URL("https://www.baidu.com/img/bd_logo1.png"), new File("D:/image.png"));
            FileUtils.copyToFile(content,new File("D:/image.png"));
        }
        response.close();
        httpClient.close();
        System.out.println("run over");
    }