天天看點

WebClient 通過get和post請求api

//get 請求

        string url = string.Format("http://localhost:28450/api/values?str1=a&str2=b");

        WebClient wc = new WebClient();

        Encoding enc = Encoding.GetEncoding("UTF-8");

        Byte[] pageData = wc.DownloadData(url);

        string re = enc.GetString(pageData);

//post 請求

        string postData = "value=a";

        byte[] bytes = Encoding.UTF8.GetBytes(postData);

        WebClient client = new WebClient();

        client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

        client.Headers.Add("ContentLength", postData.Length.ToString());

        byte[] responseData = client.UploadData("http://localhost:28450/api/values", "POST", bytes);

        string re = enc.GetString(responseData);

繼續閱讀