C#调用Post请求

    xiaoxiao2022-07-04  126

    /// <summary> /// 调用获取接口返回信息 /// </summary> /// <param name="url">接口地址</param> /// <param name="data">参数对象</param> /// <returns></returns> public string HttpPost(string url, string data) { string returnData = ""; try { //byte[] buffer = Encoding.GetEncoding("GBK").GetBytes(data); byte[] buffer = Encoding.UTF8.GetBytes(data); HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Method = "POST"; webReq.ContentType = "application/json"; webReq.ContentLength = buffer.Length; Stream postData = webReq.GetRequestStream(); postData.Write(buffer, 0, buffer.Length); postData.Close(); //HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse(); WebResponse webResp = webReq.GetResponse(); Stream answer = webResp.GetResponseStream(); StreamReader answerData = new StreamReader(answer); returnData = answerData.ReadToEnd(); } catch (Exception e) { WriteSQLErrorToFile("调用接口:" + url + "\r\n" + e.Message + "\r\n" + e.StackTrace); return ""; } return returnData.Trim(); }

     

    最新回复(0)