• C#使用HttpWebRequest发送请求


    使用HttpWebRequest可以帮助我们发送web请求

            //发送post请求
            public string SendPostReq(string param)
            {
                string content = "";
    
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
                request.Method = "Post";
                request.ContentType = "application/json";
    
                //加basic认证
                request.Headers.Add("Authorization", "Basic " + GetAuthString());
                //请求参数
                byte[] bytes = Encoding.UTF8.GetBytes(param);
                #region 写入参数
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                #endregion
    
                //读取请求结果
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        content = reader.ReadToEnd();
                    }
                }
                return content;
            }
    
            //返回结果是否成功
            public bool IsSuccess(string content)
            {
                JObject jo = JObject.Parse(content);
                if (jo["status"].ToString() == "1")
                {
                    return true;
                }
                return false;
            }

    其中,Url为自己配置的请求地址,param为json字符串,我在里面还加入Authentication认证,内容使用base64编码

    在接收方如何判断呢

                string authHeader = this.Request.Headers["Authorization"];
                string res = "";
                if (!string.IsNullOrEmpty(authHeader))
                {
                    string token = authHeader.Substring("Basic ".Length).Trim();
                    res = Encoding.UTF8.GetString(Convert.FromBase64String(token));
                }

    res即为认证的内容

    记录编程的点滴,体会学习的乐趣
  • 相关阅读:
    原型链与继承
    js错误处理Try-catch和throw
    函数柯里化
    js函数节流
    事件委托
    innerHTML属性的内存和性能问题
    微信小程序左滑显示按钮demo
    this的作用
    前端工作面试经典问题(超级全)
    HTML5入门指南
  • 原文地址:https://www.cnblogs.com/AduBlog/p/15031282.html
Copyright © 2020-2023  润新知