jsonbyte.Length);postStream.Close(); // 发送请求并获取相应回应数据 HttpW

时间:2022-02-16 06:14:29

public static string HttpPost(string url, Dictionary<String, String> param) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //创建请求 CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; //request.AllowReadStreamBuffering = true; request.MaximumResponseHeadersLength = 1024; request.Method = "POST"; //请求方法为post request.AllowAutoRedirect = true; request.MaximumResponseHeadersLength = 1024; request.ContentType = "application/json"; JObject json = new JObject(); if (param.Count != 0) //将参数添加到json东西中 { foreach (var item in param) { json.Add(item.Key, item.Value); } } string jsonstring = json.ToString();//获得参数的json字符串 byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring); Stream postStream = request.GetRequestStream(); postStream.Write(jsonbyte, 0, jsonbyte.Length); postStream.Close(); //发送请求并获取相应回应数据 HttpWebResponse res; try { res = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { res = (HttpWebResponse)ex.Response; } StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); string content = sr.ReadToEnd(); //获得响应字符串 return content; }