2017-10-14 95 views
3

我想在C#中编写这个curl脚本的等效代码。我卷曲脚本如下:使用C#中的API密钥从HttpClient类中使用PostAsync方法

我已经写了
curl -X POST \ 
https://example.com/login \ 
-H 'api-key: 11111111' \ 
-H 'cache-control: no-cache' \ 
-H 'content-type: application/json' \ 
-d '{ 
"username": "[email protected], 
"password": "mypassword" 
}' 

相应的C#代码如下:

  async static void PostRequest() 
     { 
      string url="example.com/login" 
      var formData = new List<KeyValuePair<string, string>>(); 
      formData.Add(new KeyValuePair<string, string>("username", "[email protected]")); 
      formData.Add(new KeyValuePair<string, string>("password", "mypassword")); 
      HttpContent q = new FormUrlEncodedContent(formData); 
      // where do I put my api key? 
      using (HttpClient client = new HttpClient()) 
      { 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header 
       client.BaseAddress = new Uri(url); 
       using (HttpResponseMessage response = await client.PostAsync(url, q)) 
       { 
        using (HttpContent content =response.Content) 
        { 
         string mycontent = await content.ReadAsStringAsync(); 


        } 
       } 
      } 

     } 

我的问题是我怎么包括API密钥我的要求?

回答

2

对于您要调用的Api,它看起来好像密钥在标题中。
所以使用:

client.DefaultRequestHeaders.Add("api-key", "11111111"); 
+0

它需要去头 – user3841581

+1

它按预期工作 – user3841581

相关问题