在C#中从URL获取JSON数据

4

我刚接触 JSON,想要从链接中获取 JSON 数据。在网上搜索后,我写了以下代码:

    private void button1_Click(object sender, EventArgs e)
    {
        string url = @"http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers";
        using (WebClient wc=new WebClient())
        {
                json = wc.DownloadString(url);
        }

        string path = @"ouptputfileJSON.json";

        if (!File.Exists(path))
        {
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine(json);
            }
        }
    }

当我执行此代码时,输出在HTML页面中。如何在提供的链接中获取所选产品的JSON数据?
2个回答

1

嗨,@Willem Evertse,我使用上述的intershop链接,在Unity中按照此格式link创建了购物车系统。这个Web Site链接在运行着的网站。当我添加商品到购物车时,网站上没有显示购物车。 - Amarnath
我不确定我理解这个问题,但如果您想使用Intershop的Basket REST API,您需要遵循他们的流程,而不是创建自己的流程。请参阅此链接https://support.intershop.com/kb/index.php/Display/260Q29,了解如何使用REST API与Intershop集成的详细信息。如果您对Intershop有疑问,请使用Intershop标签发布问题,相关人员将会帮助您。 - Willem Evertse

0

因为

http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers

是网页而不是 API 端点,所以您需要从您想要获取数据的正确端点中找到适当的端点。

一旦您获得了正确的端点,您可以使用以下方法:

这是一个示例,说明如何使用 httpclient 发出请求。

static void Main()
{
    Task t = new Task(DownloadPageAsync);
    t.Start();
    Console.WriteLine("Downloading page...");
    Console.ReadLine();
}

static async void DownloadPageAsync()
{
    // ... Endpoint
    string page = "request URL";

    // ... Use HttpClient.
    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(page))
    using (HttpContent content = response.Content)
    {
        // ... Read the string.
        string result = await content.ReadAsStringAsync();
        Console.WriteLine(result);
    }
}

很抱歉我作为一个开发者真的是新手,所以请告诉我如何找到端点或如何创建API端点。 - Amarnath
这是一个很好的教程,可以教你如何在 .net 中制作 Web API。http://www.tutorialsteacher.com/webapi/test-web-api - Mihir Dave
你说过没有适当的终点,这意味着.html或.aspx或其他任何东西都应该在那里给出。 - Amarnath
当您对.aspx或.html页面进行get调用时,它将始终提供HTML数据,因为这就是它们的作用。另一方面,API将根据请求和配置向您提供JSON/XML或任何其他格式,因为这就是它们的作用。因此,您不能从aspx或html期望JSON。 - Mihir Dave
所以要获取JSON数据,我必须实现这个API并且需要访问网站代码。 - Amarnath
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接