java上传下载视频的代码
时间: 2024-03-29 18:37:28 浏览: 85
以下是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);
//发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
response.close();
httpClient.close();
```
下载视频:
```java
String url = "http://example.com/video.mp4"; //下载视频地址
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
//发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
//将响应内容写入本地文件
FileOutputStream fileOutputStream = new FileOutputStream("video.mp4"); //本地文件名
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
inputStream.close();
response.close();
httpClient.close();
```
这段代码使用Apache HttpComponents库实现,需要在项目中引入httpclient和httpcore两个包。
阅读全文