以下是一个示例代码,演示如何使用 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/oYsh 著作权归作者所有。请勿转载和采集!

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