使用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即为认证的内容