技术交流QQ群 933925017
java httpClient Digest Auth 认证
因为项目需要,请求海康摄像头,进行抓图以及云台控制等功能, 海康有http协议,但是需要进行请求头认证,因为海康给的资料已经过时,所以找了很久
1.先上postMan测试通过
2.httpClient代码 - 发送普通的请求
DefaultHttpClient httpclient = new DefaultHttpClient();
String hostUrl = "http://172.16.1.11";
// 抓图
// String url = hostUrl + "/ISAPI/Streaming/channels/1/picture";
// 获取焦距
String url = hostUrl + "/ISAPI/PTZCtrl/channels/1/absoluteEx/capabilities";
// 172.16.1.11/ISAPI/PTZCtrl/channels/1/capabilities
URI serverURI = new URI(url);
HttpGet httpGet = new HttpGet(url);
String username = "admin";
String password = "abcd1234";
Credentials creds = new UsernamePasswordCredentials(username,
password);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(serverURI.getHost(), serverURI.getPort()), (Credentials) creds);
HttpResponse response = httpclient.execute(httpGet);
String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject object = Xml2Json.xml2Json(resultString);
System.out.println(object);
3.httpClient 下载图片
// 抓图
public static void download(String url, String filePathName) throws URISyntaxException {
DefaultHttpClient httpclient = new DefaultHttpClient();
URI serverURI = new URI(url);
String username = "admin";
String password = "abcd1234";
Credentials creds = new UsernamePasswordCredentials(username,
password);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(serverURI.getHost(), serverURI.getPort()), (Credentials) creds);
try {
HttpGet httpget = new HttpGet(url);
//伪装成google的爬虫JAVA问题查询
httpget.setHeader("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
File storeFile = new File(filePathName);
FileOutputStream output = new FileOutputStream(storeFile);
// 得到网络资源的字节数组,并写入文件
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
byte b[] = new byte[1024];
int j = 0;
while ((j = instream.read(b)) != -1) {
output.write(b, 0, j);
}
output.flush();
output.close();
} catch (IOException ex) {
throw ex;
} catch (RuntimeException ex) {
httpget.abort();
throw ex;
} finally {
try {
instream.close();
} catch (Exception ignore) {
}
}
}
} catch (Exception e) {
// logger.error(e.getMessage(), e);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
4.核心代码,设置请求认证
DefaultHttpClient httpclient = new DefaultHttpClient();
URI serverURI = new URI(url);
String username = "admin";
String password = "abcd1234";
Credentials creds = new UsernamePasswordCredentials(username,
password);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(serverURI.getHost(), serverURI.getPort()), (Credentials) creds);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)