/// <summary>
///Requires that all instantiations of HttpClient come from here. Global only one instance, not using
///Requests are separated and can be linked again
/// </summary>
public class HttpClientFactory
{
    private static HttpClient _HttpClient = null;
    static HttpClientFactory()
    {
        _HttpClient = new HttpClient(new HttpClientHandler());
    }
    public static HttpClient GetHttpClient()
    {
        return_HttpClient; }}/// <summary>
///WebApi all follow the Http protocol, HttpMethod
///In fact, it is equivalent to the web page, you can go to the crawler
///The backend simulates Http requests
/// 
/// HttpWebRequest  HttpClient
/// 
/// HttpClient
///Using (var HTTP = new HttpClient(handler)
///If this is done in a high union fashion, there will be an active denial of insufficient resources
///HttpClient has an internal connection pool, and requests are separated from each other. The actual use of reusable links should be singleton
/// </summary>
[TestClass]
public class WebapiTest{[TestMethod]
    public void TestMethod()
    {
        this.AuthorizationDemo();

        var result1 = this.GetClient();
        var result2 = this.GetWebQuest();
        var result3 = this.PostClient();
        var result4 = this.PostWebQuest();
        var result5 = this.PutClient();
        var result6 = this.PutWebQuest();
        var result7 = this.DeleteClient();// The value can only be a URL
        var result8 = this.DeleteWebQuest();
        //Console.WriteLine();
    }

    #region HttpClient Get
    /// <summary>
    ///HttpClient implements Get requests
    /// </summary>
    private string GetClient()
    {
        //string url = "http://localhost:8088/api/users/GetUserByName? username=superman";
        //string url = "http://localhost:8088/api/users/GetUserByID? id=1";
        //string url = "http://localhost:8088/api/users/GetUserByNameId? userName=Superman&id=1";
        //string url = "http://localhost:8088/api/users/Get";
        //string url = "http://localhost:8088/api/users/GetUserByModel? UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
        string url = "http://localhost:8088/api/users/GetUserByModelUri? UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
        //string url = "http://localhost:8088/api/users/GetUserByModelSerialize? userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
        //string url = "http://localhost:8088/api/users/GetUserByModelSerializeWithoutGet? userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
        //string url = "http://localhost:8088/api/users/NoGetUserByModelSerializeWithoutGet? userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
        var handler = new HttpClientHandler();//{ AutomaticDecompression = DecompressionMethods.GZip };

        using (var http = new HttpClient(handler))
        {
            var response = http.GetAsync(url).Result;// get the asynchronous result
            Console.WriteLine(response.StatusCode); // Ensure the HTTP success status value
            / / await asynchronous read last JSON (note that the gzip automatically extract had been made, and because of the above AutomaticDecompression = DecompressionMethods. Gzip)
            returnresponse.Content.ReadAsStringAsync().Result; }}#endregion

    #regionHttpWebRequest implements Get requests
    /// <summary>
    ///HttpWebRequest implements Get requests
    /// </summary>
    private string GetWebQuest()
    {
        //string url = "http://localhost:8088/api/users/GetUserByName? username=superman";
        //string url = "http://localhost:8088/api/users/GetUserByID? id=1";
        //string url = "http://localhost:8088/api/users/GetUserByNameId? userName=Superman&id=1";
        //string url = "http://localhost:8088/api/users/Get";
        //string url = "http://localhost:8088/api/users/GetUserByModel? UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
        //string url = "http://localhost:8088/api/users/GetUserByModelUri? UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
        string url = "http://localhost:8088/api/users/GetUserByModelSerialize? userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
        //string url = "http://localhost:8088/api/users/GetUserByModelSerializeWithoutGet? userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
        //string url = "http://localhost:8088/api/users/NoGetUserByModelSerializeWithoutGet? userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Timeout = 30 * 1000;

        //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
        //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
        string result = "";
        using (var res = request.GetResponse() as HttpWebResponse)
        {
            if (res.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = newStreamReader(res.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); }}return result;
    }

    #endregion

    #regionHttpClient implements Post requests
    /// <summary>
    ///HttpClient implements Post requests
    /// </summary>
    private string PostClient()
    {
        //string url = "http://localhost:8088/api/users/register";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        / / {" ", "1"}
        / /};

        //string url = "http://localhost:8088/api/users/RegisterNoKey";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        / / {" ", "1"}
        / /};

        //string url = "http://localhost:8088/api/users/RegisterUser";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        // {"UserID","11" },
        // {"UserName","Eleven" },
        // {"UserEmail","[email protected]" },
        / /};

        string url = "http://localhost:8088/api/users/RegisterObject";
        Dictionary<string.string> dic = new Dictionary<string.string>()
        {
            {"User[UserID]"."11" },
            {"User[UserName]"."Eleven" },
            {"User[UserEmail]"."[email protected]" },
            {"Info"."this is muti model"}}; HttpClientHandler handler =new HttpClientHandler();
        using (var http = new HttpClient(handler))
        {
            // Use FormUrlEncodedContent for HttpContent
            var content = new FormUrlEncodedContent(dic);
            var response = http.PostAsync(url, content).Result;
            Console.WriteLine(response.StatusCode); // Ensure the HTTP success status value
            returnresponse.Content.ReadAsStringAsync().Result; }}#endregion

    #regionHttpWebRequest implements post requests
    /// <summary>
    ///HttpWebRequest implements post requests
    /// </summary>
    private string PostWebQuest()
    {
        //string url = "http://localhost:8088/api/users/register";
        //var postData = "1";

        //string url = "http://localhost:8088/api/users/RegisterNoKey";
        //var postData = "1";

        var user = new
        {
            UserID = "11",
            UserName = "Eleven",
            UserEmail = "[email protected]"
        };
        //string url = "http://localhost:8088/api/users/RegisterUser";
        //var postData = JsonHelper.ObjectToString(user);

        var userOther = new
        {
            User = user,
            Info = "this is muti model"
        };
        string url = "http://localhost:8088/api/users/RegisterObject";
        var postData = Newtonsoft.Json.JsonConvert.SerializeObject(userOther);

        var request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Timeout = 30 * 1000;// Set the timeout to 30 seconds
        request.UserAgent = "Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
        request.ContentType = "application/json";
        request.Method = "POST";
        byte[] data = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = data.Length;
        Stream postStream = request.GetRequestStream();
        postStream.Write(data, 0, data.Length);
        postStream.Close();

        string result = "";
        using (var res = request.GetResponse() as HttpWebResponse)
        {
            if (res.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = newStreamReader(res.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); }}return result;
    }
    #endregion

    #regionHttpClient implements Put requests
    /// <summary>
    ///HttpClient implements Put requests
    /// </summary>
    private string PutClient()
    {
        string url = "http://localhost:8088/api/users/RegisterPut";
        Dictionary<string.string> dic = new Dictionary<string.string>()
        {
            {""."1"}};//string url = "http://localhost:8088/api/users/RegisterNoKeyPut";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        / / {" ", "1"}
        / /};

        //string url = "http://localhost:8088/api/users/RegisterUserPut";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        // {"UserID","11" },
        // {"UserName","Eleven" },
        // {"UserEmail","[email protected]" },
        / /};

        //string url = "http://localhost:8088/api/users/RegisterObjectPut";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        // {"User[UserID]","11" },
        // {"User[UserName]","Eleven" },
        // {"User[UserEmail]","[email protected]" },
        // {"Info","this is muti model" }
        / /};

        HttpClientHandler handler = new HttpClientHandler();
        using (var http = new HttpClient(handler))
        {
            // Use FormUrlEncodedContent for HttpContent
            var content = new FormUrlEncodedContent(dic);
            var response = http.PutAsync(url, content).Result;
            Console.WriteLine(response.StatusCode); // Ensure the HTTP success status value
            returnresponse.Content.ReadAsStringAsync().Result; }}#endregion

    #regionHttpWebRequest implements the PUT request
    /// <summary>
    ///HttpWebRequest implements the PUT request
    /// </summary>
    private string PutWebQuest()
    {
        //string url = "http://localhost:8088/api/users/registerPut";
        //var postData = "1";

        //string url = "http://localhost:8088/api/users/RegisterNoKeyPut";
        //var postData = "1";

        var user = new
        {
            UserID = "11",
            UserName = "Eleven",
            UserEmail = "[email protected]"
        };
        //string url = "http://localhost:8088/api/users/RegisterUserPut";
        //var postData = JsonHelper.ObjectToString(user);

        var userOther = new
        {
            User = user,
            Info = "this is muti model"
        };
        string url = "http://localhost:8088/api/users/RegisterObjectPut";
        var postData = Newtonsoft.Json.JsonConvert.SerializeObject(userOther);

        var request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Timeout = 30 * 1000;// Set the timeout to 30 seconds
        request.UserAgent = "Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
        request.ContentType = "application/json";
        request.Method = "PUT";
        byte[] data = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = data.Length;
        Stream postStream = request.GetRequestStream();
        postStream.Write(data, 0, data.Length);
        postStream.Close();

        string result = "";
        using (var res = request.GetResponse() as HttpWebResponse)
        {
            if (res.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = newStreamReader(res.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); }}return result;
    }
    #endregion

    #regionHttpClient implements Delete requests
    /// <summary>
    ///HttpClient implements Put requests
    ///No data put in
    /// </summary>
    private string DeleteClient()
    {
        string url = "http://localhost:8088/api/users/RegisterDelete/1";
        Dictionary<string.string> dic = new Dictionary<string.string>()
        {
            {""."1"}};//string url = "http://localhost:8088/api/users/RegisterNoKeyDelete";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        / / {" ", "1"}
        / /};

        //string url = "http://localhost:8088/api/users/RegisterUserDelete";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        // {"UserID","11" },
        // {"UserName","Eleven" },
        // {"UserEmail","[email protected]" },
        / /};

        //string url = "http://localhost:8088/api/users/RegisterObjectDelete";
        //Dictionary<string, string> dic = new Dictionary<string, string>()
        / / {
        // {"User[UserID]","11" },
        // {"User[UserName]","Eleven" },
        // {"User[UserEmail]","[email protected]" },
        // {"Info","this is muti model" }
        / /};

        HttpClientHandler handler = new HttpClientHandler();
        using (var http = new HttpClient(handler))
        {
            // Use FormUrlEncodedContent for HttpContent
            var content = new FormUrlEncodedContent(dic);
            var response = http.DeleteAsync(url).Result;
            Console.WriteLine(response.StatusCode); // Ensure the HTTP success status value
            returnresponse.Content.ReadAsStringAsync().Result; }}#endregion

    #regionHttpWebRequest implements the PUT request
    /// <summary>
    ///HttpWebRequest implements the PUT request
    /// </summary>
    private string DeleteWebQuest()
    {
        //string url = "http://localhost:8088/api/users/registerDelete";
        //var postData = "1";

        //string url = "http://localhost:8088/api/users/RegisterNoKeyDelete";
        //var postData = "1";

        var user = new
        {
            UserID = "11",
            UserName = "Eleven",
            UserEmail = "[email protected]"
        };
        //string url = "http://localhost:8088/api/users/RegisterUserDelete";
        //var postData = JsonHelper.ObjectToString(user);

        var userOther = new
        {
            User = user,
            Info = "this is muti model"
        };
        string url = "http://localhost:8088/api/users/RegisterObjectDelete";
        var postData = Newtonsoft.Json.JsonConvert.SerializeObject(userOther);

        var request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Timeout = 30 * 1000;// Set the timeout to 30 seconds
        request.UserAgent = "Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
        request.ContentType = "application/json";
        request.Method = "Delete";
        byte[] data = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = data.Length;
        Stream postStream = request.GetRequestStream();
        postStream.Write(data, 0, data.Length);
        postStream.Close();

        string result = "";
        using (var res = request.GetResponse() as HttpWebResponse)
        {
            if (res.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = newStreamReader(res.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); }}return result;
    }
    #endregion


    #regionThe user logs in to obtain ticket
    private void AuthorizationDemo()
    {
        string ticket = "";
        {
            string loginUrl = "http://localhost:8088/api/users/Login? Account=Admin&Password=123456";
            var handler = new HttpClientHandler();//{ AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                var response = http.GetAsync(loginUrl).Result;// get the asynchronous result
                Console.WriteLine(response.StatusCode); // Ensure the HTTP success status value
                                                        / / await asynchronous read last JSON (note that the gzip automatically extract had been made, and because of the above AutomaticDecompression = DecompressionMethods. Gzip)
                ticket = response.Content.ReadAsStringAsync().Result.Replace("\"{\\\"Result\\\":true,\\\"Ticket\\\":\\\""."").Replace("\ \ \"} \ ""."");
                //ticket = JsonHelper.StringToObject<TicketModel>(response.Content.ReadAsStringAsync().Result).Ticket;}} {string url = "http://localhost:8088/api/users/GetUserByName? username=superman";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 30 * 1000;
            request.Headers.Add(HttpRequestHeader.Authorization, "BasicAuth " + ticket);// Add Authorization to header files
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = newStreamReader(res.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); }}} {string url = "http://localhost:8088/api/users/GetUserByName? username=superman";
            var handler = new HttpClientHandler();

            using (var http = new HttpClient(handler))
            {
                http.DefaultRequestHeaders.Add("Authorization"."BasicAuth " + ticket);// Add Authorization to header files
                var response = http.GetAsync(url).Result;
                Console.WriteLine(response.StatusCode);
                stringresult = response.Content.ReadAsStringAsync().Result; }}}#endregion
}
Copy the code