代码之家  ›  专栏  ›  技术社区  ›  Sam

使用httpclient从c调用Shopware API

  •  0
  • Sam  · 技术社区  · 6 年前

    我试图从C_调用Shopware rest API。SuoWWORKS有使用CURL调用API的文档,并且大部分我可以将其转换为C*I和HTTPclipse,但是对于一些选项,我不知道要设置什么标题:

    该商店位于一个基本的htaccess身份验证之后,并且具有使用apikey的shopware身份验证。我的代码:

    var handler = new System.Net.Http.HttpClientHandler { Credentials = new NetworkCredential(htaccessUsername, htaccessPassword) });
    var client = new System.Net.Http.HttpClient(handler);
    
    using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl + "orders?limit=20"))
    {
      var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{apiKey}"));
      var authorizationKey = "Basic" + " " + encodedStr;
      requestMessage.Headers.Add("Authorization", authorizationKey);
      // curl_setopt($this->cURL, CURLOPT_RETURNTRANSFER, true);
      // curl_setopt($this->cURL, CURLOPT_FOLLOWLOCATION, false);
      // curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
      // curl_setopt(
      //    $this->cURL,
      //    CURLOPT_HTTPHEADER,
      //    ['Content-Type: application/json; charset=utf-8']
      // );
      using (var responseMessage = await client.SendAsync(requestMessage))
      {
        var data = await responseMessage.Content.ReadAsStringAsync();
        System.Diagnostics.Trace.WriteLine(data);
      }
    }
    

    基本htaccess身份验证正在工作,但Shopware身份验证确实失败,数据中有以下响应:

    "{\"success\":false,\"message\":\"Invalid or missing auth\"}"
    

    我想我需要实现 curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); 在c_中,但是我没有找到如何将这些curl选项转换为头的线索。 有什么帮助吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   d_f    6 年前

    看来你的答案是 here :

    var credCache = new CredentialCache();
    var basicCred = new NetworkCredential(htaccessUsername, htaccessPassword);
    var digestCred = new NetworkCredential(username, apiKey);
    credCache.Add(new Uri("http://.com/"), "Basic", basicCred);
    credCache.Add(new Uri("http://.com/"), "Digest", digestCred);
    var httpClient = new HttpClient(new HttpClientHandler { Credentials = credCache });