1. 程式人生 > >Java微型瀏覽器——HttpClient 4.5.6簡要學習總結

Java微型瀏覽器——HttpClient 4.5.6簡要學習總結

原料:

MAVEN匯入

  <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

例1:Get網頁並存盤

        CloseableHttpClient defaultHttpClient = HttpClients.createDefault();

        HttpGet hg = new HttpGet("http://www.k99sam.com/photos/list");

        //設定cookie
        hg.setHeader("cookie", "t=ea927b137ec52d665a842efa2e5eb5bc9; path=/; domain=.k99sam.com; Expires=Tue, 19 Jan 2038 03:14:07 GMT;");

        HttpResponse httpResponse = defaultHttpClient.execute(hg);

        File f1 = new File("temp.html");

        InputStream is =  httpResponse.getEntity().getContent();

        //這裡用EntityUtils獲得原始網頁程式碼文字,HTTP.UTF_8已過時了,用StandardCharsets.UTF_8替代!
        String srcHtml = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);

        FileOutputStream fos = new FileOutputStream(f1);

        fos.write(srcHtml.getBytes());

        fos.close();

例2:Get圖片或檔案資源

        CloseableHttpClient defaultHttpClient = HttpClients.createDefault();

        HttpGet hg = new HttpGet("http://www.k99sam.com/photos/yourwife.jpg");

        hg.setHeader("cookie","t=ea927b137ec52d665a842efa2e5eb5bc9; path=/; domain=.k99sam.com; Expires=Tue, 19 Jan 2038 03:14:07 GMT;");

        HttpResponse httpResponse = defaultHttpClient.execute(hg);

        File f1 = new File("test.jpg");

        InputStream is =  httpResponse.getEntity().getContent();

        FileOutputStream fos = new FileOutputStream(f1);

        byte[] buf = new byte[1024 * 1024];

        int size;

        while ((size = is.read(buf)) != -1){
            fos.write(buf,0,size);
        }

        fos.close();

        is.close();

        hg.releaseConnection();

例3:傳送Post請求

        CloseableHttpClient defaultHttpClient = HttpClients.createDefault();
          
        //用BasicNameValuePair製作引數
        List<BasicNameValuePair> paramList = new ArrayList<>();

        paramList.add(new BasicNameValuePair("username","k99sam"));
        paramList.add(new BasicNameValuePair("password","123456"));

        HttpPost hp = new HttpPost("http://www.k99sam.com/addUser");

        //引數實體,注意編碼!
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList,StandardCharsets.UTF_8);

        hp.setHeader("cookie","t=ea927b137ec52d665a842efa2e5eb5bc9; path=/; domain=.k99sam.com; Expires=Tue, 19 Jan 2038 03:14:07 GMT;");

        //設定body的實體
        hp.setEntity(urlEncodedFormEntity);

        HttpResponse httpResponse = defaultHttpClient.execute(hp);

        if (httpResponse.getStatusLine().getStatusCode() == 200){
            //do something....
        }
        hp.releaseConnection();