How to use WebRequest to POST some data and read response?

后端 未结 5 434
南方客
南方客 2021-02-01 06:03

Need to have the server make a POST to an API, how do I add POST values to a WebRequest object and how do I send it and get the response (it will be a string) out?

I nee

5条回答
  •  礼貌的吻别
    2021-02-01 07:05

    Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

    const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
    //This string is untested, but I think it's ok.
    string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
    try
    {       
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "POST";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
    
        using (System.IO.Stream s = webRequest.GetRequestStream())
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
                sw.Write(jsonData);
        }
    
        using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
            {
                var jsonResponse = sr.ReadToEnd();
                System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
            }
        }
    }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.ToString());
    }
    

提交回复
热议问题