【问题标题】:HttpClient post request with Digest Authentication results in bad request具有摘要身份验证的 HttpClient 发布请求导致错误请求
【发布时间】:2021-10-25 11:17:53
【问题描述】:

我正在使用以下代码从大华XVR相机中提取记录,并成功返回记录。

        var domain = "http://IP";
        var credCache = new CredentialCache();
        credCache.Add(new Uri(domain), "Digest", new 
        NetworkCredential(username, password));
        var httpClient = new HttpClient(new HttpClientHandler { 
        Credentials = credCache });
        var result= await httpClient.GetStringAsync(new Uri(URL));   

但是当我使用以下代码发布记录时,它不起作用并导致错误的请求。

        string url = "http://IP/cgi-bin/faceRecognitionServer.cgi";

        var postData = new List<KeyValuePair<string, string>>()
        {
        new KeyValuePair<string, string>( "action", "addPerson"),
        new KeyValuePair<string, string>("groupID", "1"),
        new KeyValuePair<string, string>("name", "Test Name"),
        new KeyValuePair<string, string>("birthday", "1980-01-05"),
        new KeyValuePair<string, string>("sex", "Male"),
        new KeyValuePair<string, string>("country", "Pakistan"),
        new KeyValuePair<string, string>("province", "KPK"),
        new KeyValuePair<string, string>("city", "Peshawar")
        };
        var content = new FormUrlEncodedContent(postData);

        var domain = "http://IP";
        var credCache = new CredentialCache();
        credCache.Add(new Uri(domain), "Digest", new NetworkCredential(username, password));
        var httpClient = new HttpClient(new HttpClientHandler { Credentials = credCache });
        var result = await httpClient.PostAsync(new Uri(url), content);

上面的代码总是返回 400 bad request。有人可以帮忙吗?

【问题讨论】:

  • 问题可能与url有关

标签: c# authentication post hash httpclient


【解决方案1】:

我解决了如下问题。也许它可以帮助某人。

  1. 减小了我必须在请求中嵌入的图像的大小 身体。

  2. 将 URL 和参数连接在一个字符串中。

       string url = "http://IP/cgi-bin/faceRecognitionServer.cgi? 
                    action=addPerson&groupID=1&name=TestName&sex=Male";
    
      string domain = "http://IP";
      CredentialCache credCache = new CredentialCache {
            {
             new Uri(domain), "Digest", new NetworkCredential(username, 
             password)
            }
        };
     using HttpClient client = new HttpClient(new HttpClientHandler { 
     Credentials = credCache });
    
     using FileStream stream = 
    
    
    File.OpenRead(AppContext.BaseDirectory.
    Replace("\\bin\\Debug\\netcoreapp3.1", "") + "Files\\14.jpg");
    
    var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
        file_content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        var response = await client.PostAsync(url, file_content);
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-02
    • 2013-05-23
    • 1970-01-01
    • 2020-11-21
    • 2020-07-10
    • 2011-05-07
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多