具有摘要身份验证的 HttpClient 发布请求导致错误请求

Posted

技术标签:

【中文标题】具有摘要身份验证的 HttpClient 发布请求导致错误请求【英文标题】:HttpClient post request with Digest Authentication results in bad request 【发布时间】: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有关 【参考方案1】:

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

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

    将 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);
    

【讨论】:

以上是关于具有摘要身份验证的 HttpClient 发布请求导致错误请求的主要内容,如果未能解决你的问题,请参考以下文章

使用当前 httpclient (4.x) 的 RestTemplate 基本或摘要身份验证

Ruby:摘要代理身份验证

具有身份验证的 Apache HttpClient Socks5 代理

具有不同身份验证标头的 HttpClient 单个实例

.NET WebApi HttpClient 未将 Windows 身份验证凭据发送到同一域

使用 HttpURLConnection 进行摘要式身份验证