我正在尝试使用HttpClient在C#中进行以下卷曲(对我有用)。
I am trying to do the following curl (which works for me) in C# using HttpClient.
curl -X POST www.somehosturl \ -u <client-id>:<client-secret> \ -d 'grant_type=password' \ -d 'username=<email>' \ -d 'password=<password>' \ -d 'scope=allC#代码:
HttpClientHandler handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential ("my_client_id", "my_client_secret") }; try { using(var httpClient = new HttpClient(handler)) { var activationUrl = "www.somehosturl"; var postData = "grant_type=password&username=myemail@myemail&password=mypass&scope=all"; var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync(activationUrl, content); if(!response.IsSuccessStatusCode) return null; var result = await response.Content.ReadAsStringAsync(); return result; } } catch(Exception) { return null; }执行后,它崩溃了,甚至没有捕获到异常
When executed, just crashes out, doesnt even catch the exception
通常我能够进行GET和POST完全正常,但是让我失望的是如何设置身份验证内容(client-id和client-secret)
Normally I am able to GET and POST perfectly fine, but whats throwing me off is how to set the auth stuff (client-id and client-secret)
推荐答案首先,必须使用<设置 Authorization -Header。 clientid> 和< clientsecret> 。
First you have to set the Authorization-Header with your <clientid> and <clientsecret>.
而不是使用 StringContent ,您应该使用 FormUrlEncodedContent ,如下所示:
Instead of using StringContent you should use FormUrlEncodedContent as shown below:
var client = new HttpClient(); client.BaseAddress = new Uri("myserver"); var request = new HttpRequestMessage(HttpMethod.Post, "/path"); var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); var formData = new List<KeyValuePair<string, string>>(); formData.Add(new KeyValuePair<string, string>("grant_type", "password")); formData.Add(new KeyValuePair<string, string>("username", "<email>")); formData.Add(new KeyValuePair<string, string>("password", "<password>")); formData.Add(new KeyValuePair<string, string>("scope", "all")); request.Content = new FormUrlEncodedContent(formData); var response = await client.SendAsync(request);更多推荐
如何使用HttpClient发布身份验证
发布评论