4.1 认证
客户端程序向设备发送请求时,需要使用摘要认证(详见RFC 7616)完成身份认证。
客户程序只需要简单地调用类库接口即可完成摘要认证过程,示例源码如下。
4.1.1 C/C++ (libcurl)
// #include <curl/curl.h>
// 回调函数
static size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid)
{
std::string* str = dynamic_cast<std::string*>((std::string *)lpVoid);
if( NULL == str || NULL == buffer )
{
return -1;
}
char* pData = (char*)buffer;
str->append(pData, size * nmemb);
return nmemb;
}
std::string strUrl = "http://192.168.18.84:80/ISAPI/System/deviceInfo";
std::string strResponseData;
CURL *pCurlHandle = curl_easy_init();
curl_easy_setopt(pCurlHandle, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(pCurlHandle, CURLOPT_URL, strUrl.c_str());
// 设置用户名和密码
curl_easy_setopt(pCurlHandle, CURLOPT_USERPWD, "admin:admin12345");
// 设置认证方式为摘要认证
curl_easy_setopt(pCurlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
// 设置回调函数
curl_easy_setopt(pCurlHandle, CURLOPT_WRITEFUNCTION, OnWriteData);
// 设置回调函数的参数,获取反馈信息
curl_easy_setopt(pCurlHandle, CURLOPT_WRITEDATA, &strResponseData);
// 接收数据时超时设置,如果5秒内数据未接收完,直接退出
curl_easy_setopt(pCurlHandle, CURLOPT_TIMEOUT, 5);
// 设置重定向次数,防止重定向次数太多
curl_easy_setopt(pCurlHandle, CURLOPT_MAXREDIRS, 1);
// 连接超时,这个数值如果设置太短可能导致数据请求不到就断开了
curl_easy_setopt(pCurlHandle, CURLOPT_CONNECTTIMEOUT, 5);
CURLcode nRet = curl_easy_perform(pCurlHandle);
if (0 == nRet)
{
// 输出接收的消息
std::cout << strResponseData << std::endl;
}
curl_easy_cleanup(pCurlHandle);
4.1.2 C# (WebClient)
// using System.Net;
// using System.Net.Security;
try
{
string strUrl = "http://192.168.18.84:80/ISAPI/System/deviceInfo";
WebClient client = new WebClient();
// 设置用户名和密码
client.Credentials = new NetworkCredential("admin", "admin12345");
byte[] responseData = client.DownloadData(strUrl);
string strResponseData = Encoding.UTF8.GetString(responseData);
// 输出接收的消息
Console.WriteLine(strResponseData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
4.1.3 Java (HttpClient)
// import org.apache.commons.httpclient.HttpClient;
String url = "http://192.168.18.84:80/ISAPI/System/deviceInfo";
HttpClient client = new HttpClient();
// 设置用户名和密码
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin",
"admin12345");
client.getState().setCredentials(AuthScope.ANY, creds);
GetMethod method = new GetMethod(url);
method.setDoAuthentication(true);
int statusCode = client.executeMethod(method);
byte[] responseData =
method.getResponseBodyAsString().getBytes(method.getResponseCharSet());
String strResponseData = new String(responseData, "utf-8");
method.releaseConnection();
// 输出接收的消息
System.out.println(strResponseData);
……