WebAPI :GetPostDeletePut

Posted 三线小码农

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebAPI :GetPostDeletePut相关的知识,希望对你有一定的参考价值。

public class RestClientMethod
    {
        /// <summary>
        /// 请求服务器地址
        /// </summary>
        public string BaseUri;        //例如: http://10.0.0.193
        public RestClientMethod(string baseUri)
        {
            this.BaseUri = baseUri;
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="strAuth_token"></param>
        /// <returns></returns>
        public string Get(string uri, string strAuth_token)
        {
            string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri);     //先根据用户请求的uri构造请求地址 
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl);    //创建访问对象  
            myRequest.Headers.Add("Authorization", strAuth_token);      //需要auth_token验证时添加,没有可去掉,下同
            HttpWebResponse myResponse;     //通过访问对象获取响应内容
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
            }
            catch (WebException ex)
            {
                myResponse = (HttpWebResponse)ex.Response;
                Console.WriteLine(ex.Response);
            }
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);     //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题
            string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                                                  //reader提供多种数据转换类型,如reader.ReadAsync可转换为所设定的实体类型
            reader.Close();
            myResponse.Close();
            return returnXml;
        }

        #region Post请求
        /// <summary>
        /// 登录获取权限POST底层方法
        /// </summary>
        /// <param name="data">数据参数</param>
        /// <param name="uri">API接口path</param>
        /// <returns></returns>
        public string PostJsonData(string data, string uri, string strAgent)
        {
            //先根据用户请求的uri构造请求地址
            string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri);
            //创建Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl);      
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);  //数据转成“UTF-8”的字节流    //设置参数的编码格式,解决中文乱码 
            myRequest.Method = "POST";
            myRequest.ContentLength = buf.Length;     //设置myRequest的MIME类型及内容长度
            if (strAgent != "")
            {
                myRequest.UserAgent = strAgent;
            }
            myRequest.ContentType = "application/json"; 
            using (Stream stream = myRequest.GetRequestStream())    //发送请求
            {
                stream.Write(buf, 0, buf.Length);
                stream.Close();
            }
            using (WebResponse myResponse = (WebResponse)myRequest.GetResponse())  //获取接口返回值  通过Web访问对象获取响应内容   
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))    //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                {
                    //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题
                    string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                    reader.Close();
                    myResponse.Close();
                    return returnXml;
                }
            }
        }

        /// <summary>
        /// json格式执行Post方法
        /// </summary>
        /// <param name="data"></param>
        /// <param name="uri"></param>
        /// <param name="strtoken"></param>
        /// <returns></returns>
        public string PostJsonWithAuth(string data, string uri, string strtoken)
        {
            string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl);
            myRequest.Method = "POST";
            myRequest.Headers.Add("Authorization", strtoken);
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            //发送请求
            using (Stream stream = myRequest.GetRequestStream())
            {
                stream.Write(buf, 0, buf.Length);
                stream.Close();
            }
            using (WebResponse myResponse = (WebResponse)myRequest.GetResponse())  //获取接口返回值  通过Web访问对象获取响应内容   
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))    //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                {
                    //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题
                    string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                    reader.Close();
                    myResponse.Close();
                    return returnXml;
                }
            }
        }


        /// <summary>
        /// form-data格式执行Post方法   传图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="imageInfo"></param>
        /// <param name="stringDict"></param>
        /// <param name="strAuth_token"></param>
        /// <returns></returns>
        public string PostFormData(string url, Dictionary<string, string> imageInfo, System.Collections.Specialized.NameValueCollection stringDict, string strAuth_token)
        {
            string responseContent = "";
            try
            {
                string serviceUrl = string.Format("{0}/{1}", this.BaseUri, url);
                var webRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                webRequest.Headers.Add("Authorization", strAuth_token);
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");    // 边界符  
                // 设置属性                                                                     
                webRequest.Method = "POST";
                webRequest.Timeout = 10000;    //默认超时时间为10秒
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "
");   // 开始边界符  
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--
");   // 最后的结束符 
                var memStream = new MemoryStream();    //为系统内存提供流式的读写操作
                memStream.Write(beginBoundary, 0, beginBoundary.Length);

                FileStream fileStream = null;
                #region 写入文件 
                if (imageInfo != null)
                {
                    foreach (var item in imageInfo)
                    {
                        fileStream = null;
                        fileStream = new FileStream(item.Value, FileMode.Open, FileAccess.Read);
                        const string filePartHeader = "Content-Disposition: form-data; name="{0}"; filename="{1}"
" + "Content-Type: application/octet-stream

";
                        var header = string.Format(filePartHeader, item.Key, item.Value);
                        var headerbytes = Encoding.UTF8.GetBytes(header);
                        memStream.Write(headerbytes, 0, headerbytes.Length);
                        var buffer = new byte[1024];
                        int bytesRead; // =0   
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            memStream.Write(buffer, 0, bytesRead);
                        }
                    }
                }
                #endregion

                var contentLine = Encoding.ASCII.GetBytes("
");
                memStream.Write(contentLine, 0, contentLine.Length);
                // 写入字符串的Key  
                var stringKeyHeader = "
--" + boundary +
                                       "
Content-Disposition: form-data; name="{0}"" +
                                       "

{1}
";
                if (stringDict != null)
                {
                    foreach (byte[] formitembytes in from string key in stringDict.Keys
                                                     select string.Format(stringKeyHeader, key, stringDict[key])
                                                         into formitem
                                                     select Encoding.UTF8.GetBytes(formitem))
                    {
                        memStream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                // 写入最后的结束边界符  
                memStream.Write(endBoundary, 0, endBoundary.Length);
                webRequest.ContentLength = memStream.Length;
                var requestStream = webRequest.GetRequestStream();
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                using (var httpWebResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                                    Encoding.GetEncoding("utf-8")))
                    {
                        responseContent = httpStreamReader.ReadToEnd();
                    }
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                    httpWebResponse.Close();
                    webRequest.Abort();
                }
            }
            catch (Exception ex)
            {
                responseContent = ex.ToString();
            }
            return responseContent;
        }


        #endregion

        #region Put请求 
        public string PutWithToken(string uri, string info, string strToken)
        {
            string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl);      //后台或可使用WebRequest request = WebRequest.Create(url);
            myRequest.Headers.Add("Authorization", strToken);                                                                          //数据转成“UTF-8”的字节流    //设置参数的编码格式,解决中文乱码
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(info);
            myRequest.Method = "Put";
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            //myRequest.MaximumAutomaticRedirections = 1;
            //myRequest.AllowAutoRedirect = true;
            //发送请求
            using (Stream stream = myRequest.GetRequestStream())
            {
                stream.Write(buf, 0, buf.Length);
                stream.Close();
            }
            using (WebResponse myResponse = (WebResponse)myRequest.GetResponse())  //获取接口返回值  通过Web访问对象获取响应内容   
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))    //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                {
                    //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题
                    string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                    reader.Close();
                    myResponse.Close();
                    return returnXml;
                }
            }
        }

        #endregion

        #region Delete请求
        public string Delete(string data, string uri, string strServerToken)
        {
            string serviceUrl = string.Format("{0}{1}", this.BaseUri, uri);
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(serviceUrl);      
            myRequest.Headers.Add("Authorization", strServerToken);
            myRequest.Method = "DELETE";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            //myRequest.MaximumAutomaticRedirections = 1;
            //myRequest.AllowAutoRedirect = true;
            if (data != "")
            {
                byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
                myRequest.ContentLength = buf.Length; 
                using (Stream stream = myRequest.GetRequestStream())   //发送请求
                {
                    stream.Write(buf, 0, buf.Length);
                    stream.Close();
                } 
            } 
            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())  //获取接口返回值  通过Web访问对象获取响应内容   
            {
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))    //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                {
                    //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//解决编码问题
                    string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                    reader.Close();
                    myResponse.Close();
                    return returnXml;
                }
            }
        }


        #endregion

    }

以上是关于WebAPI :GetPostDeletePut的主要内容,如果未能解决你的问题,请参考以下文章

Spring的Restful

1-3 接口基础知识面试题

SpringBoot 学习笔记心得请求参数处理

ASP.NET Core Authorization

职男说:WCF Service API 网关

asp.net web api c# interface dataprovider