httpClient调用海康威视/ISAPI/Streaming/channels/1/picture接口的代码
时间: 2023-11-11 19:07:18 浏览: 172
JAVA 调用HTTP接口POST或GET实现方式
以下是使用HttpClient调用海康威视/ISAPI/Streaming/channels/1/picture接口的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpTest {
public static void main(String[] args) throws ClientProtocolException, IOException {
String url = "http://192.168.1.1/ISAPI/Streaming/channels/1/picture";
String username = "admin";
String password = "admin123";
String auth = "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
HttpHost proxy = new HttpHost("127.0.0.1", 8888);
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpUriRequest request = new HttpGet(url);
request.setHeader("Authorization", auth);
request.setConfig(requestConfig);
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
byte[] data = EntityUtils.toByteArray(entity);
try (FileOutputStream fos = new FileOutputStream("image.jpg")) {
fos.write(data);
}
}
}
}
}
```
注意,这里使用了Basic认证,需要将用户名和密码进行Base64编码后添加到请求头中。另外,如果需要使用代理,可以通过设置RequestConfig来指定代理。最后,将图片数据保存到本地文件中。
阅读全文