用HttpClient写一个获取视频流的请求方法
时间: 2023-05-27 11:07:43 浏览: 175
以下是一个使用HttpClient获取视频流的示例代码:
```java
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class VideoStreamHttpClient {
public static void main(String[] args) throws IOException {
String url = "http://example.com/video.mp4";
String outputFilePath = "video.mp4";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
try {
InputStream inputStream = httpClient.execute(httpGet).getEntity().getContent();
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
inputStream.close();
System.out.println("Video stream saved to " + outputFilePath);
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.close();
}
}
}
```
这个示例代码使用HttpClient发送了一个GET请求来获取视频流,并将其保存到本地文件中。需要修改`url`和`outputFilePath`变量以适应你的情况。注意,这个示例代码并没有处理HTTP响应的状态码和错误信息,实际应用中需要根据需要进行相应的处理。
阅读全文