使用java下载一首歌(HttpClient/JavaIO)

  • 需要HttpClient的支持,而且需要手动在主函数调用一次。
  • 音乐或文件链接以及本地URL因时因地而异。
  • 初学,望各位大神指点!
package httptest;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientTest
{
   public void download()
    {
        try
        {
            CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet("http://mvvideo1.meitudata.com/57199f5ceb9288320.mp4");
            HttpResponse httpResponse = closeableHttpClient.execute(httpGet);

            System.out.println(httpResponse.getStatusLine());
            System.out.println("获取服务器响应成功!");

            for (org.apache.http.Header header : httpResponse.getAllHeaders())
            {
                System.out.println(header.getName() +":"+ header.getValue());
            }

            HttpEntity entity = httpResponse.getEntity();

            InputStream inputStream = entity.getContent();
            long len = entity.getContentLength();

            File file = new File("C:\\Users\\LiuZijian\\Desktop\\21.mp4");
            OutputStream outputStream = new FileOutputStream(file);
            int current = 0;

            byte data[] = new byte[10];
            int length = 0;

            while ((length = inputStream.read(data)) != -1)
            {
                outputStream.write(data,0,length);
                current += length;
                System.out.println("下载进度 :" + (float) current/(float)len);
            }

            inputStream.close();
            outputStream.close();
            System.out.println("下载成功!");

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值