HTTP request call in post mode (input parameter in JSON format)

Time:2021-1-28

To sum up today, call the address of the third-party interface, make HTTP request by post, and input parameters are in JSON format

Reference: Using System.Text ;using System.Net ;using System.IO ;

String url = “http: / /”; / / third party interface address

Paramstr / / JSON string input parameter

Encoding encoding = Encoding.UTF8;

Call: httpresult result = gethttpnewweb (URL, paramstr, encoding)

public HttpResult GetHttpNewWeb(string url, string paramStr,  Encoding encoding)
        {
          
            HttpResult r = new HttpResult();
            string responseString = string.Empty;
            HttpWebRequest myRequest =null;
            HttpWebResponse myResponse = null;
            try
            {
                //JObject jobj = new JObject(new JProperty("json", paramStr));
                byte[] data =Encoding.UTF8.GetBytes(paramStr);
                 myRequest =  HttpWebRequest.Create (URL) as Httpwebrequest; // note that myrequest = (Httpwebrequest) cannot be written here WebRequest.Create (url);
                DateTime start_time = DateTime.Now;
                myRequest.Timeout = 60000;
                myRequest.Method = "POST";
                myRequest.ContentType = "application/json";
                using (Stream stream = myRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length); 

                }
                HttpWebResponse EhealthResp = myRequest.GetResponse() as HttpWebResponse;
                Stream EhealthResu = EhealthResp.GetResponseStream();
                StreamReader EhealthSr = new StreamReader(EhealthResu, Encoding.GetEncoding("UTF-8"));
                string finalStr = EhealthSr.ReadToEnd();
                r.result = true;
                r.html = finalStr;
                return r;
            }
            catch (Exception ex)
            {
                r.html = ex.ToString();
                if (myRequest != null) myRequest.Abort();
                if (myResponse != null) myResponse.Close();
                return r;
            }

            r. HTML = "call completed, URL address" + URL;
            r.result = false;
            return r;
        }

string  fanhuizhi = result.html;