C#--调用WebApi--(Get,Post,Put,Delete请求总结)

以下是学习笔记:

一,HttpWebRequest方式

1,WebRequest方式 Get请求

  

        #region 方法3 .WebRequest方式 Get请求
        public static string HttpWebRequest_Get(string url)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            Encoding encoding = Encoding.UTF8;

            //构造一个Web请求的对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            //获取web请求的响应的内容
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            //string ss = HttpWebRequest_Get("http://localhost:55837/api/product");
            string ss = HttpWebRequest_Get(txt_get_url.Text);
            this.textBox3.Text += ss;
        }

        #endregion

  

 

 

2,WebRequest方式 Get带参数请求

        #region WebRequest方式 Get带参数请求

        private void button6_Click(object sender, EventArgs e)
        {
            string id = this.txt_get_parameter.Text;
            string ss = HttpWebRequest_Get(txt_get_url.Text+ "?"+id.Trim());//带参数
            this.textBox6.Text += ss;
        }


        #endregion

  

 

 

 

 

3,WebRequest方式 Post请求

        #region 方法3 WebRequest方式 Post请求

        public static string HttpWebRequest_Post(string url, string body)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.Method = "POST"; //Post请求方式
            request.Accept = "text/html, application/xhtml+xml, */*";
            // 内容类型
            //request.ContentType = "application/json";//参数格式:  {username:"admin",password:"123} 如果参数不是json类型会报错
            request.ContentType =
                "application/x-www-form-urlencoded"; //参数:username=admin&password=123 如果参数是json格式或者参数写错不会报错的

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);

            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //上面的代码会有异常出现,更改如下:

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }


            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string url = this.txt_post_url.Text;
            string body = this.txt_post_parameter.Text;
            string ss = HttpWebRequest_Post(url, body);
            this.textBox4.Text += ss;
        }

        #endregion

  

 

 

  

4,HttpWebRequest方式 Delete请求:

 #region WebRequest方式 Delete请求
        /// <summary>
        ///  API发送DELETE请求,返回状态:200成功,201失败
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string HttpWebRequest_Delete(string url)
        {
            //Web访问对象64
            //string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            string serviceUrl = url;
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            myRequest.Method = "DELETE";
            // 获得接口返回值68
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();
            return ReturnXml;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (txt_delete_parameter.Text.Trim().Length > 0)
            {
                HttpWebRequest_Delete(txt_delete_rul.Text+"?"+txt_delete_parameter.Text);//带参数删除
            }
            else
            {
                HttpWebRequest_Delete(txt_delete_rul.Text);//全部删除
            }
            
        }

  

 

 5,HttpWebRequest方式 Put请求:

       见下面的通用方法

二,HttpClient 方式

1,HttpClient 方式 Get请求

  #region 方法4 HttpClient 方式 Get请求

        public static string HttpClienGet(string url)
        {
            HttpClient hc = new HttpClient();
            string html= hc.GetStringAsync(url).Result;
            return html;
        }

        private void btn_HttpClentGet_Click(object sender, EventArgs e)
        {
            string url = this.txt_get_url.Text;
            string html = HttpClienGet(url);
            txt_HttpClentGet_Result.Text += html;
        }

        #endregion

  

2,HttpClient 方式 Post请求

        #region 方法4 HttpClient 方式 Post请求

        public static async void HttpClientPost(string url)
        {
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None };

            using (var httpclient = new HttpClient(handler))
            {
                httpclient.BaseAddress = new Uri(url);
                var content = new FormUrlEncodedContent(new Dictionary<string, string>()
                {
                    {"name", "杜宗英"},
                    {"age", "18"},
                    {"gender","false" }
                });

                var  response = await httpclient.PostAsync(url, content);

                string responseString = await response.Content.ReadAsStringAsync();
                MessageBox.Show(responseString);
            }
        }

       

        private void button5_Click(object sender, EventArgs e)
        {
            string url = this.txt_post_url.Text;
            HttpClientPost(url);

        }
        #endregion

 

三,WebClient 方式

1,WebClient方式 Post请求

        #region WebClient方式 Post请求
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body">传递的参数</param>
        /// <returns></returns>
        public static string WebClientPost(string url,string body)
        {
            byte[] postData = Encoding.UTF8.GetBytes(body);//编码,尤其是汉字,事先要看下抓取网页的编码方式
            WebClient webClient=new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
            byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流  
            string srcString = Encoding.UTF8.GetString(responseData);//解码 
            return srcString;
        }

        private void btn_WebClient_Post_Click(object sender, EventArgs e)
        {
            string url = this.txt_post_url.Text;
            string body = this.txt_post_parameter.Text;
            string srcString = WebClientPost(url, body);
            this.txt_WebClient_Post.Text += srcString;
        }

        #endregion

 

四,HttpWebRequest通用方法

        public string CommonHttpWebRequest(string data, string uri, string type)
        {
            //Web访问对象,构造请求的url地址
            //string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
            string serviceUrl = uri;

            //构造http请求的对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //转成网络流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
            //设置
            request.Method = type;
            request.ContentLength = buf.Length;
            //myRequest.ContentType = "application/json";//如果参数不是json格式会报错
            request.ContentType ="application/x-www-form-urlencoded";
            request.MaximumAutomaticRedirections = 1;
            request.AllowAutoRedirect = true;
            // 发送请求
            Stream newStream = request.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();
            // 获得接口返回值
            //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //上面的代码会有异常出现,更改如下:

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string ReturnXml = reader.ReadToEnd();
            reader.Close();
            response.Close();
            return ReturnXml;
        }

  1,Delete请求代码:

        private void btn_webapi_delete_Click(object sender, EventArgs e)
        {
            string url = txt_delete_rul.Text;
            string data = txt_delete_parameter.Text;

            if (data.Trim().Length > 0)
            {
                CommonHttpWebRequest(data, url + "?" + data, "DELETE");//带参数删除
            }
            else
            {
                CommonHttpWebRequest(data, url, "DELETE"); ;//全部删除
            }
            
        }

  2,Post请求代码:

        private void btn_webapi_post_Click(object sender, EventArgs e)
        {
            string url = txt_post_url.Text;
            string data = txt_post_parameter.Text;

            string res = CommonHttpWebRequest(data, url, "POST");
            this.txt_webapi_get_data.Text += res;
        }

  3,Put 请求代码:

        private void btn_webapi_put_Click(object sender, EventArgs e)
        {
            string url = txt_put_url.Text;
            string data = txt_put_parameter.Text;

            string res = CommonHttpWebRequest(data, url, "PUT");
            this.txt_webapi_get_data.Text += res;
        }

  

 

 

 

 

 

 

posted @ 2020-10-10 22:06  包子789654  阅读(8428)  评论(1编辑  收藏  举报