HttpClient獲取網頁中的內容,并實現圖片和視頻的下載功能

1.HttpClient

  • httpclient可以拿到其他項目或者URL下的內容

2.HttpClient用法

  • 獲取其他頁面中的內容,和已知路徑下載圖片和視頻
a.添加依賴
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.10</version>
        </dependency>
    </dependencies>
b.新建一個HttpClientUtils.java類
package com.ym.utils;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * ClassName: HttpClientUtils
 * Description: 可以獲取指定路徑下的網頁中的內容
 * date: 2020/5/2  14:11
 *
 * @author YanM
 * @since JDK 1.8
 */
public class HttpClientUtils {

    /**
     * 獲取指定baseURL鏈接所返回的字符串數據
     * @param baseURL
     * @return
     */
    public static String getDataFromURL(String baseURL){
        try {
            //根據URL創建一個URL對象
            URL url=new URL(baseURL);
            //通過URL對象的openConnection()方法,強轉的到一個httpURLConnection
            HttpURLConnection con=(HttpURLConnection) url.openConnection();
            //設置請求的超時時間
            con.setConnectTimeout(5000);
            //設置請求的請求方式
            con.setRequestMethod("GET");
            //設置請求方式為輸入請求
            con.setDoInput(true);
            //得到請求返回的狀態碼
            int code=con.getResponseCode();

            //如果狀態碼是HTTP_OK(200)
            if (code==HttpURLConnection.HTTP_OK){
                //通過連接對象的getInputStream()方法的到一個輸入流對象
                InputStream is=con.getInputStream();
                ByteArrayOutputStream baos=new ByteArrayOutputStream();

                byte[] bytes=new byte[8192];

                int len;
                while ((len=is.read(bytes))!=-1){
                    baos.write(bytes,0,len);
                }
                return new String(baos.toByteArray());
            }

        } catch (MalformedURLException | ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根據指定的baseURL來獲取該url對應的字節數組的值
     * @param baseURL   要獲取數據的url
     * @param type      請求類型 GET活著POST
     * @return 指定baseURL所對應的字節數組值
     * 可以實現圖片和視頻的下載功能
     */
    public static byte[] getByteDataByURL(String baseURL,String type){
        try {
            URL url=new URL(baseURL);
            HttpURLConnection con=(HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5000);

            if ("GET".equalsIgnoreCase(type)){
                con.setRequestMethod("GET");
            }else {
                con.setRequestMethod("POST");
            }

            con.setDoInput(true);

            int code=con.getResponseCode();

            if (code==HttpURLConnection.HTTP_OK){
                InputStream is=con.getInputStream();

                ByteArrayOutputStream baos=new ByteArrayOutputStream();

                int len;
                byte[] data=new byte[8192];

                while ((len=is.read(data))!=-1){
                    baos.write(data,0,len);
                }
                return baos.toByteArray();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
c.測試功能
import com.ym.utils.HttpClientUtils;
import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * ClassName: HttpClientUtilsUtilsTest
 * Description:
 * date: 2020/5/2  14:59
 *
 * @author YanM
 * @since JDK 1.8
 */
public class HttpClientUtilsUtilsTest {

    //獲取網頁中的信息
    @Test
    public void testGetData(){
        String data = HttpClientUtils.getDataFromURL("http://localhost:8080/users/getAll");
        System.out.println(data);
    }

    /**
     * 實現下載圖片和視頻的功能
     * http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4
     * https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218114723HDu3hhxqIT.mp4
     */
    @Test
    public void testGetByteData() throws IOException {
        //byte[] datas = HttpClientUtils.getByteDataByURL("http://t9.baidu.com/it/u=1307125826,3433407105&fm=79&app=86&f=JPEG?w=5760&h=3240", "get");
        //下載圖片

        byte[] datas = HttpClientUtils.getByteDataByURL("https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218114723HDu3hhxqIT.mp4", "get");
        //下載視頻
        FileOutputStream fos=null;
        try {
            //fos=new FileOutputStream("gile.jpg");
            //下載到本地圖片的名字

            fos=new FileOutputStream("hello.mp4");
            //下載到本地的視頻

            fos.write(datas);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                if (fos!=null){
                    fos.close();
                    fos=null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("download success");
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。