使用HttpURLConnection下载网络文件

前言:

最近产品经理要分析用户的行为数据,于是让我将生产上的数据包都下载下来,用HttpURLConnection和Java的IO流,挺方便,下面简单介绍一下。

下载代码

public static void testDownLoad(){
         BufferedInputStream  bis =null;
         BufferedOutputStream bos=null;
         String HTTP_URL="http://f0.topitme.com/0/7a/63/113144393585b637a0o.jpg"; //图片地址
             try {
                 int contentLength = getConnection(HTTP_URL).getContentLength();
                 System.out.println("文件的大小是:"+contentLength);
                 if (contentLength>32) {
                     InputStream is= getConnection(HTTP_URL).getInputStream();
                     bis = new BufferedInputStream(is);
                     FileOutputStream fos = new FileOutputStream("C:/test/美女.jpg");
                     bos= new BufferedOutputStream(fos);
                     int b = 0;
                     byte[] byArr = new byte[1024];
                     while((b= bis.read(byArr))!=-1){
                         bos.write(byArr, 0, b);
                     }
                     System.out.println("下载的文件的大小是----------------------------------------------:"+contentLength);
                 }

             } catch (Exception e) {
                 e.printStackTrace();
             }finally{
                 try {
                     if(bis !=null){
                         bis.close();
                     }
                     if(bos !=null){
                         bos.close();
                     }
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
     }

连接HttpURLConnection代码

public static HttpURLConnection getConnection(String httpUrl) throws Exception {
        URL url = new URL(httpUrl);
        HttpURLConnection connection =  (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.connect();
        return connection;

 }

Main方法调用代码

public static void main(String[] args) {
       testDownLoad();
 }

下载效果

这里写图片描述

图片有点性感啊,别介意,连接失效,大家自己在百度上搜一张图片,然后复制图片地址替换代码中的连接即可!

猜你喜欢

转载自blog.csdn.net/u013067402/article/details/79569942