我想在C#中编写这个curl脚本的等价物。我的curl脚本如下:
curl -X POST \
https://example.com/login \
-H 'api-key: 11111111' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{
"username": "myemail@hotmail.com,
"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", "myemail@hotmail.com"));
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密钥?
答案 0 :(得分:3)
对于您正在呼叫的Api,似乎密钥位于标题中 所以使用:
unsigned replace(char *cp){
unsigned cnt;
for(cnt = 0; *cp ; cp++) {
switch (*cp){
case ' ' : case '\t': case '\n':
*cp = '-';
cnt++;
default:
break;
}
}
return cnt;
}