• C# 后台访问webapi


    具体在哪看见的忘记了。

    异步:

    public static class CallWebAPI
        {
            public static async Task<string> APIPost(string url, string data)
            {
                string result = string.Empty;
                //设置HttpClientHandler的AutomaticDecompression
                var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
                //创建HttpClient(注意传入HttpClientHandler)
                using (var http = new HttpClient(handler))
                {
                    //使用FormUrlEncodedContent做HttpContent
                    var content = new FormUrlEncodedContent(new Dictionary<string, string>()       
                    {
    //传递单个值
                      {"", data}//键名必须为空
    //传递对象
    //{"name","hello"},
    //{"age","16"}
                     });
    
                    //await异步等待回应
                    var response = await http.PostAsync(url, content);
                    //确保HTTP成功状态值
                    response.EnsureSuccessStatusCode();
                    //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                    result = await response.Content.ReadAsStringAsync();
                }
                return result;
            }
    
            static async void APIGet(string url)
            {
                //创建HttpClient(注意传入HttpClientHandler)
                var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
    
                using (var http = new HttpClient(handler))
                {
                    //await异步等待回应
                    var response = await http.GetAsync(url);
                    //确保HTTP成功状态值
                    response.EnsureSuccessStatusCode();
    
                    //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                    Console.WriteLine(await response.Content.ReadAsStringAsync());
                }
            }
        }

    同步:

    public static class RequestUtility
        {
            #region 同步方法
    
            /// <summary>
            /// 使用Get方法获取字符串结果(没有加入Cookie)
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static string HttpGet(string url, Encoding encoding = null)
            {
                WebClient wc = new WebClient();
                wc.Encoding = encoding ?? Encoding.UTF8;
                //if (encoding != null)
                //{
                //    wc.Encoding = encoding;
                //}
                return wc.DownloadString(url);
            }
    
            /// <summary>
            /// 使用Get方法获取字符串结果(加入Cookie)
            /// </summary>
            /// <param name="url"></param>
            /// <param name="cookieContainer"></param>
            /// <param name="encoding"></param>
            /// <returns></returns>
            public static string HttpGet(string url, CookieContainer cookieContainer = null, Encoding encoding = null, int timeOut = 10000)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.Timeout = timeOut;
    
                if (cookieContainer != null)
                {
                    request.CookieContainer = cookieContainer;
                }
    
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
                if (cookieContainer != null)
                {
                    response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                }
    
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
                    {
                        string retString = myStreamReader.ReadToEnd();
                        return retString;
                    }
                }
            }
    
            /// <summary>
            /// 使用Post方法获取字符串结果,常规提交
            /// </summary>
            /// <returns></returns>
            public static string HttpPost(string url, CookieContainer cookieContainer = null, Dictionary<string, string> formData = null, Encoding encoding = null, int timeOut = 10000)
            {
                MemoryStream ms = new MemoryStream();
                formData.FillFormDataStream(ms);//填充formData
                return HttpPost(url, cookieContainer, ms, null, null, encoding, timeOut);
            }
    
            /// <summary>
            /// 使用Post方法获取字符串结果
            /// </summary>
            /// <param name="url"></param>
            /// <param name="cookieContainer"></param>
            /// <param name="postStream"></param>
            /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名</param>
            /// <param name="timeOut"></param>
            /// <returns></returns>
            public static string HttpPost(string url, CookieContainer cookieContainer = null, Stream postStream = null, Dictionary<string, string> fileDictionary = null, string refererUrl = null, Encoding encoding = null, int timeOut = 10000)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Timeout = timeOut;
    
                #region 处理Form表单文件上传
                var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件
                if (formUploadFile)
                {
                    //通过表单上传文件
                    postStream = postStream ?? new MemoryStream();
    
                    string boundary = "----" + DateTime.Now.Ticks.ToString("x");
                    //byte[] boundarybytes = Encoding.ASCII.GetBytes("
    --" + boundary + "
    ");
                    string fileFormdataTemplate = "
    --" + boundary + "
    Content-Disposition: form-data; name="{0}"; filename="{1}"
    Content-Type: application/octet-stream
    
    ";
                    string dataFormdataTemplate = "
    --" + boundary +
                                                  "
    Content-Disposition: form-data; name="{0}"
    
    {1}";
                    foreach (var file in fileDictionary)
                    {
                        try
                        {
                            var fileName = file.Value;
                            //准备文件流
                            using (var fileStream = FileHelper.GetFileStream(fileName))
                            {
                                string formdata = null;
                                if (fileStream != null)
                                {
                                    //存在文件
                                    formdata = string.Format(fileFormdataTemplate, file.Key, /*fileName*/ Path.GetFileName(fileName));
                                }
                                else
                                {
                                    //不存在文件或只是注释
                                    formdata = string.Format(dataFormdataTemplate, file.Key, file.Value);
                                }
    
                                //统一处理
                                var formdataBytes = Encoding.ASCII.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行
                                postStream.Write(formdataBytes, 0, formdataBytes.Length);
    
                                //写入文件
                                if (fileStream != null)
                                {
                                    byte[] buffer = new byte[1024];
                                    int bytesRead = 0;
                                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        postStream.Write(buffer, 0, bytesRead);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    //结尾
                    var footer = Encoding.ASCII.GetBytes("
    --" + boundary + "--
    ");
                    postStream.Write(footer, 0, footer.Length);
    
                    request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                }
                else
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                #endregion
    
                request.ContentLength = postStream != null ? postStream.Length : 0;
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                request.KeepAlive = true;
    
                if (!string.IsNullOrEmpty(refererUrl))
                {
                    request.Referer = refererUrl;
                }
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
    
                if (cookieContainer != null)
                {
                    request.CookieContainer = cookieContainer;
                }
    
                #region 输入二进制流
                if (postStream != null)
                {
                    postStream.Position = 0;
    
                    //直接写入流
                    Stream requestStream = request.GetRequestStream();
    
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }
    
    
                    //debug
                    postStream.Seek(0, SeekOrigin.Begin);
                    StreamReader sr = new StreamReader(postStream);
                    var postStr = sr.ReadToEnd();
    
    
                    postStream.Close();//关闭文件访问
                }
                #endregion
    
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
                if (cookieContainer != null)
                {
                    response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                }
    
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8")))
                    {
                        string retString = myStreamReader.ReadToEnd();
                        return retString;
                    }
                }
            }
    
            #endregion
    
            /// <summary>
            /// 组装QueryString的方法
            /// 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3
            /// </summary>
            /// <param name="formData"></param>
            /// <returns></returns>
            public static string GetQueryString(this Dictionary<string, string> formData)
            {
                if (formData == null || formData.Count == 0)
                {
                    return "";
                }
    
                StringBuilder sb = new StringBuilder();
    
                var i = 0;
                foreach (var kv in formData)
                {
                    i++;
                    sb.AppendFormat("{0}={1}", kv.Key, kv.Value);
                    if (i < formData.Count)
                    {
                        sb.Append("&");
                    }
                }
    
                return sb.ToString();
            }
    
            /// <summary>
            /// 填充表单信息的Stream
            /// </summary>
            /// <param name="formData"></param>
            /// <param name="stream"></param>
            public static void FillFormDataStream(this Dictionary<string, string> formData, Stream stream)
            {
                string dataString = GetQueryString(formData);
                var formDataBytes = formData == null ? new byte[0] : Encoding.UTF8.GetBytes(dataString);
                stream.Write(formDataBytes, 0, formDataBytes.Length);
                stream.Seek(0, SeekOrigin.Begin);//设置指针读取位置
            }
    
            /// <summary>
            /// 封装System.Web.HttpUtility.HtmlEncode
            /// </summary>
            /// <param name="html"></param>
            /// <returns></returns>
            public static string HtmlEncode(this string html)
            {
                return System.Web.HttpUtility.HtmlEncode(html);
            }
            /// <summary>
            /// 封装System.Web.HttpUtility.HtmlDecode
            /// </summary>
            /// <param name="html"></param>
            /// <returns></returns>
            public static string HtmlDecode(this string html)
            {
                return System.Web.HttpUtility.HtmlDecode(html);
            }
            /// <summary>
            /// 封装System.Web.HttpUtility.UrlEncode
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static string UrlEncode(this string url)
            {
                return System.Web.HttpUtility.UrlEncode(url);
            }
            /// <summary>
            /// 封装System.Web.HttpUtility.UrlDecode
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public static string UrlDecode(this string url)
            {
                return System.Web.HttpUtility.UrlDecode(url);
            }
        }


    FileHelper.cs

    public class FileHelper
        {
            /// <summary>
            /// 根据完整文件路径获取FileStream
            /// </summary>
            /// <param name="fileName"></param>
            /// <returns></returns>
            public static FileStream GetFileStream(string fileName)
            {
                FileStream fileStream = null;
                if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
                {
                    fileStream = new FileStream(fileName, FileMode.Open);
                }
                return fileStream;
            }
        }

     下面这个也可以试试。

    /// <summary>
            /// Post获取信息
            /// </summary>
            /// <typeparam name="T">实体对象</typeparam>
            /// <param name="url">post url</param>
            /// <param name="data">post json data</param>
            /// <returns></returns>
            public static T PostOfUrl<T>(string url, string data)
            {
                System.Net.HttpWebRequest httpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
                httpWebRequest.Method = "POST";
    
                httpWebRequest.Headers.Add("Accept-Charset", "utf-8");
    
                byte[] postBytes = Encoding.UTF8.GetBytes(data);
                //httpWebRequest.ContentType = "text/xml"; 
                httpWebRequest.ContentType = "application/json; charset=utf-8";// httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(data);//strJson为json字符串 
                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(postBytes, 0, postBytes.Length);
                stream.Close();//发送完毕,接受返回值 
                var response = httpWebRequest.GetResponse();
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                String responseString = streamRead.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                var list = js.Deserialize<T>(responseString);
                return list;
            }
    
            public static T GetOfUrl<T>(string url)
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                string respHtml = sr.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                var list = js.Deserialize<T>(respHtml);
                return list;
            }
  • 相关阅读:
    圆形按钮窗口控制-不断减少的圆圈
    图像按钮和模拟Windows媒体播放器UI
    圆形按钮
    本机Win32主题感知所有者绘制控件没有MFC
    CRegionButton -一个多向按钮
    Iconits
    CxShadeButton
    管道符 |
    gedit
    more/less
  • 原文地址:https://www.cnblogs.com/hanjun0612/p/9779844.html
Copyright © 2020-2023  润新知