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());
        Encoding enc = Encoding.GetEncoding("UTF-8");
        byte[] responseData = client.UploadData("http://localhost:28450/api/values", "POST", bytes);
        string re = enc.GetString(responseData);

posted @ 2017-09-19 10:14  左正  阅读(403)  评论(0编辑  收藏  举报