将参数添加到httpclient

编码

我在Postman中写了一个HTTP请求,我想在我的应用程序中写同样的请求。邮递员中有一个选项可以查看C#请求的代码。在邮递员中,它使用RestSharp显示请求,因为我不想在项目中使用外部NuGet包,因此我试图使用.NET Framework中的对象编写相同的请求。

RestSharp代码如下所示:

var client = new RestClient("https://login.microsoftonline.com/04xxxxa7-xxxx-4e2b-xxxx-89xxxx1efc/oauth2/token");
var request = new RestRequest(Method.POST);       
request.AddHeader("Host", "login.microsoftonline.com");            
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "grant_type=password&client_id=6e97fc60-xxx-445f-xxxx-a9b1bbc9eb2d&client_secret=4lS*xxxxxYn%5BENP1p%2FZT%2BpqmqF4Q&resource=https%3A%2F%2Fgraph.microsoft.com&username=myNameHere%402comp.onmicrosoft.com&password=xxxxxxxxxx6", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

在此处输入图片说明

我试图用写相同的请求HttpWebRequest

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://login.microsoftonline.com/0475dfa7-xxxxxxxx-896cf5e31efc/oauth2/token");
request.Method = "GET";
request.Referer = "login.microsoftonline.com";
request.ContentType = "application/x-www-form-urlencoded";

request.Headers.Add("grant_type", "password");
request.Headers.Add("client_id", "6e97fc60-xxxxxxxxx-a9bxxxxxb2d");
request.Headers.Add("client_secret", "4lSxxxxxxxxxxxmqF4Q");
request.Headers.Add("resource", "https://graph.microsoft.com");
request.Headers.Add("username", "[email protected]");
request.Headers.Add("password", "xxxxxxxxxxxxx");

HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

但是我正在获取HTML内容,我想我不需要添加参数作为标头,这怎么实现?

Tobias Tengler

WebRequest如果可以,我不会使用,而是使用HttpClient

HttpResponseMessage resp;

using (var httpClient = new HttpClient())
{
    var req = new HttpRequestMessage(HttpMethod.Get, "https://login.microsoftonline.com/0475dfa7-xxxxxxxx-896cf5e31efc/oauth2/token");
    req.Headers.Add("Referer", "login.microsoftonline.com");
    req.Headers.Add("Accept", "application/x-www-form-urlencoded");
    req.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

    // This is the important part:
    req.Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        { "grant_type", "password" },
        { "client_id", "6e97fc60-xxxxxxxxx-a9bxxxxxb2d" },
        { "client_secret", "4lSxxxxxxxxxxxmqF4Q" },
        { "resource", "https://graph.microsoft.com" },
        { "username", "[email protected]" },
        { "password", "xxxxxxxxxxxxx" }
    });

    resp = await httpClient.SendAsync(req);
}

// Work with resp

如果您决定使用此代码,请注意,为了示例起见,我只是使用ausing并处理了该代码HttpClient通常,您不会这样做。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章