1 public class Httphelper 2 { 3 public static string Post1(string url, string postString) 4 { 5 6 using (WebClient webClient = new WebClient()) 7 { 8 byte[] postData = Encoding.UTF8.GetBytes(postString);//编码, 9 webClient.Headers.Add("Content-Type", "application/json");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可 10 byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流 11 string srcString = Encoding.UTF8.GetString(responseData);//解码 12 return srcString; 13 } 14 } 15 16 public static string Post(string url, string postData) 17 { 18 string result = ""; 19 20 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 21 22 req.Method = "POST"; 23 24 25 26 req.ContentType = "application/json"; 27 28 byte[] data = Encoding.UTF8.GetBytes(postData); 29 30 req.ContentLength = data.Length; 31 //req.Timeout = 30000; 32 using (Stream reqStream = req.GetRequestStream()) 33 { 34 reqStream.Write(data, 0, data.Length); 35 36 reqStream.Close(); 37 } 38 39 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 40 41 Stream stream = resp.GetResponseStream(); 42 43 //获取响应内容 44 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 45 { 46 result = reader.ReadToEnd(); 47 } 48 49 return result; 50 } 51 }
HttpClient 调用
1 /// <summary> 2 /// post 同步 3 /// </summary> 4 /// <param name="url"></param> 5 /// <param name="postString"></param> 6 /// <returns></returns> 7 public static string Post(string url, string postData) 8 { 9 try 10 { 11 using (HttpClient _httpClient = new HttpClient()) 12 { 13 StringContent httpClient = new StringContent(postData, Encoding.UTF8, "application/json"); 14 var response = _httpClient.PostAsync(url, httpClient).Result; 15 string jsonstr = response.Content.ReadAsStringAsync().Result; 16 return jsonstr; 17 } 18 } 19 catch (Exception ex) 20 { 21 _logger.LogError(string.Format("Api调用异常--url【{0}】,参数【{1}】", url, postData), ex); 22 return ""; 23 } 24 } 25 /// <summary> 26 /// post 异步 27 /// </summary> 28 /// <param name="url"></param> 29 /// <param name="postData"></param> 30 /// <returns></returns> 31 public static async void PostAsync(string url, string postData) 32 { 33 try 34 { 35 using (HttpClient _httpClient = new HttpClient()) 36 { 37 StringContent httpClient = new StringContent(postData, Encoding.UTF8, "application/json"); 38 var response = await _httpClient.PostAsync(url, httpClient); 39 string jsonstr = await response.Content.ReadAsStringAsync(); 40 } 41 } 42 catch (Exception ex) 43 { 44 _logger.LogError(string.Format("Api调用异常--url【{0}】,参数【{1}】", url, postData), ex); 45 } 46 }