以下是一个示例代码,演示如何使用C#远程调用外部接口:

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;

namespace RemoteAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://api.example.com/getdata";
            string data = "param1=value1&param2=value2";

            string result = RemoteCall(url, data);

            Console.WriteLine(result);
            Console.ReadLine();
        }

        static string RemoteCall(string url, string data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(data);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

在上面的代码中,我们定义了一个名为“RemoteCall”的静态方法,它接受两个参数:URL和数据。 RemoteCall方法使用HttpWebRequest对象创建了一个POST请求,将给定的数据作为请求主体发送到指定的URL。然后,我们从响应中读取并返回响应正文。

为了更好的解析响应正文,我们可以在代码中使用JavaScriptSerializer类将JSON格式的响应转换为C#对象。例如:

using System.Web.Script.Serialization;

...

static MyObject RemoteCall(string url, string data)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(data);
    }

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        string json = reader.ReadToEnd();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Deserialize<MyObject>(json);
    }
}

class MyObject
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
}

在上面的代码中,MyObject类表示我们从API获取的数据。我们使用JavaScriptSerializer类将JSON格式的响应转换为MyObject类型的实例,并返回它

C#远程调用外部接口的代码

原文地址: https://www.cveoy.top/t/topic/hvCi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录