Skip to content

C# Http post 调用 Web 接口

🏷️ C#

请求内容格式为 Json (这里使用了 Newtonsoft.Json 类库)

csharp
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;

namespace CallHttpUrl
{
    class Program
    {
        static void Main(string args)
        {
            string url = "http://localhost:8080/api/visit-count";
            string postData = JsonConvert.SerializeObject(new { clientType = "1", token = "testtoken", version  = "1.0"});

            Console.WriteLine(PostHttpApi(url, postData));
            Console.ReadLine();
        }

        static string PostHttpApi(string url, string postData)
        {
            WebRequest wRequest = WebRequest.Create(url);
            wRequest.Method = "POST";
            wRequest.ContentType = "application/json";
            wRequest.ContentLength = postData.Length;

            StreamWriter sw = new StreamWriter(wRequest.GetRequestStream());
            sw.Write(postData);
            sw.Flush();

            WebResponse wResponse = wRequest.GetResponse();
            Stream stream = wResponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream, System.Text.Encoding.Default);
            string r = reader.ReadToEnd();   //url 返回的值

            sw.Dispose();
            sw.Close();
            reader.Dispose();
            reader.Close();
            stream.Dispose();
            stream.Close();
            wResponse.Dispose();
            wResponse.Close();

            return r;
        }
    }
}