如何使用HttpClient类

时间:2016-08-10 08:31:51

标签: c# asp.net-web-api

我有一个类似的代码,其中很少有区域不清楚。所以请先看看代码。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");
request.Method = "Get";
request.KeepAlive = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.UseDefaultCredentials = true;
request.Credentials = new NetworkCredential("username", "password", "domain");
request.ContentType = "application/json";
//request.ContentType = "application/x-www-form-urlencoded";

//get cookie from Web API
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
foreach (Cookie cookieValue in response.Cookies)
{
    Console.Write("Cookie: " + cookieValue.ToString());
    //store in your winform application
}
//get content
string myResponse = "";
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
    myResponse = sr.ReadToEnd();
}

为什么这么多代码与凭证有关?

request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.UseDefaultCredentials = true;
request.Credentials = new NetworkCredential("username", "password", "domain");

我需要为域new NetworkCredential传递哪些信息("用户名","密码","域");

而不是使用HttpWebRequest如何使用http client类实现相同的效果。

0 个答案:

没有答案