码迷,mamicode.com
首页 > Windows程序 > 详细

WebAPI :Get、Post、Delete、Put

时间:2020-04-27 17:20:39      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:util   decode   his   amr   odi   mst   auto   close   内存   

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 + "\r\n");   // 开始边界符  
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");   // 最后的结束符 
                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}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
                        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("\r\n");
                memStream.Write(contentLine, 0, contentLine.Length);
                // 写入字符串的Key  
                var stringKeyHeader = "\r\n--" + boundary +
                                       "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                       "\r\n\r\n{1}\r\n";
                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 :Get、Post、Delete、Put

标签:util   decode   his   amr   odi   mst   auto   close   内存   

原文地址:https://www.cnblogs.com/NetNotes/p/12787742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!