How to use HttpClient to Post with Authentication

后端 未结 2 2056
长发绾君心
长发绾君心 2020-12-15 03:46

I am trying to do the following curl (which works for me) in C# using HttpClient.

curl -X POST http://www.somehosturl.com \\
     -u :

        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 04:04

    First you have to set the Authorization-Header with your and .

    Instead of using StringContent you should use FormUrlEncodedContent as shown below:

    var client = new HttpClient();
    client.BaseAddress = new Uri("http://myserver");
    var request = new HttpRequestMessage(HttpMethod.Post, "/path");
    
    var byteArray = new UTF8Encoding().GetBytes(":");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
    
    var formData = new List>();
    formData.Add(new KeyValuePair("grant_type", "password"));
    formData.Add(new KeyValuePair("username", ""));
    formData.Add(new KeyValuePair("password", ""));
    formData.Add(new KeyValuePair("scope", "all"));
    
    request.Content = new FormUrlEncodedContent(formData);
    var response = await client.SendAsync(request);
    

提交回复
热议问题