一、不带参数请求
/// <summary> /// POST请求不带参数 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string Post(string url) { string result;//返回结果 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream stream = response.GetResponseStream(); using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; }
二、带参数 post请求,参数传递方式json
/// <summary> /// post请求带参数 /// </summary> /// <param name="url"></param> /// <param name="param">参数字符串</param> /// <returns></returns> public static string Post(string url, string param) { //创建post请求 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST";//请求方式post request.ContentType = "application/json;charset=UTF-8";//链接类型 byte[] payload = Encoding.UTF8.GetBytes(param);//参数编码 request.ContentLength = payload.Length; //发送post的请求,写入参数 Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); //接受返回来的数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.UTF8); string value = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); return value; }
三、带参数post请求,参数传递表单
var url = ""; var client = new RestClient(url); var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddParameter("company_id", "1343BE1A6D6"); request.AddParameter("company_key", "5C9F93D44962AD10E76870772999DF92"); request.AddParameter("user_name", "柳正"); request.AddParameter("condition", JsonConvert.SerializeObject(condition)); IRestResponse response = client.Execute(request);
string res = Regex.Unescape(response.Content);