用JAVA代码实现下载网络上的资源


前面整理过基于UDP/TCP协议的网络编程,这里教大家用简单的代码实现下载网络资源的功能。在这里使用到了http协议的相关java类---URL和HttpURLConnection,关于这两个类的深入学习可以查看相关API。

以下载百度上的一张图片为例,代码如下:

package http;

//导包
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class CatchPic {
	/**
	 * 实现从指定网址获取一张图片
	 * @throws IOException 
	 */
	
	public static void main(String[] args) throws IOException {
		  //调用catchPic方法从网络上下载一张图片
                  catchPic();
	}
	public static void catchPic() throws IOException 
	{
			
			//创建URL对象,参数传递一个String类型的URL解析地址
			URL url = new URL("http://img04.tooopen.com/images/20131202/sy_49706261893.jpg");
			//HttpUR
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现上传下载视频的高效方法,可以考虑以下几点: 1. 使用多线程:多线程能够充分利用带宽,加快上传下载速度。可以使用Java的线程池来管理线程,避免线程过多导致系统资源耗尽。 2. 分块传输:将大文件分成若干个块进行传输,这样即使某一块传输失败,也不会影响整个文件的上传或下载。可以使用HTTP协议的分块传输编码(Chunked Transfer Encoding)或者自定义分块传输协议。 3. 压缩数据:对于大文件,可以在传输时进行压缩,减少传输数据量。可以使用Java的压缩库(如GZIP)进行压缩。 4. 使用CDN:通过使用CDN(内容分发网络),可以将静态资源缓存到离用户最近的节点上,加速文件的传输。 下面是Java代码实现上传下载视频的示例: 上传视频: ```java File file = new File("video.mp4"); String url = "http://example.com/upload"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); //分块上传 FileEntity fileEntity = new FileEntity(file, ContentType.DEFAULT_BINARY); httpPost.setEntity(fileEntity); //设置多线程上传 ExecutorService executorService = Executors.newFixedThreadPool(5); //开启5个线程 List<Future> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { //将文件分成5块并上传 final int partNumber = i+1; final long start = i * file.length() / 5; final long end = (i+1) * file.length() / 5 - 1; Future<?> future = executorService.submit(() -> { HttpPost httpPartPost = new HttpPost(url); httpPartPost.setHeader("Content-Range", "bytes " + start + "-" + end + "/" + file.length()); httpPartPost.setEntity(new FileEntity(file, ContentType.DEFAULT_BINARY, start, end)); CloseableHttpResponse response = httpClient.execute(httpPartPost); response.close(); }); futures.add(future); } //等待所有线程上传完成 for (Future future : futures) { try { future.get(); } catch (Exception e) { e.printStackTrace(); } } executorService.shutdown(); httpClient.close(); ``` 下载视频: ```java String url = "http://example.com/video.mp4"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); //设置多线程下载 ExecutorService executorService = Executors.newFixedThreadPool(5); //开启5个线程 List<Future> futures = new ArrayList<>(); CloseableHttpResponse response = httpClient.execute(httpGet); long contentLength = Long.parseLong(response.getFirstHeader("Content-Length").getValue()); for (int i = 0; i < 5; i++) { //将文件分成5块并下载 final int partNumber = i+1; final long start = i * contentLength / 5; final long end = (i+1) * contentLength / 5 - 1; Future<?> future = executorService.submit(() -> { HttpGet httpPartGet = new HttpGet(url); httpPartGet.setHeader("Range", "bytes=" + start + "-" + end); CloseableHttpResponse partResponse = httpClient.execute(httpPartGet); HttpEntity entity = partResponse.getEntity(); InputStream inputStream = entity.getContent(); FileOutputStream fileOutputStream = new FileOutputStream("video_" + partNumber + ".mp4"); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, len); } fileOutputStream.close(); inputStream.close(); partResponse.close(); }); futures.add(future); } //等待所有线程下载完成 for (Future future : futures) { try { future.get(); } catch (Exception e) { e.printStackTrace(); } } executorService.shutdown(); httpClient.close(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值