【问题标题】:How to get output of http request in JSON file?如何在 JSON 文件中获取 http 请求的输出?
【发布时间】:2015-07-24 08:38:06
【问题描述】:

我正在向 url 发出 http get 请求,我能够从该网页获取数据,但我无法以 JSON 格式存储它,也无法解释数据并获取所需的数据。我是使用 ASP.NET 和 C#。

这是我的 CS 文件的代码:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace httprequest_web
{
    public partial class req : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                string baseu = "http://railenquiry.in/runningstatus/";

                string url = string.Concat(baseu, TextBox1.Text);
                var request = WebRequest.Create(url);
                string text;
                var response = (HttpWebResponse)request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    request.ContentType = "application/json; charset=utf-8";
                    text = sr.ReadToEnd();
                }
                Label1.Text = text;
            }
            catch
            {
                Label1.Text = "No Data Found";
            }
            }

        }
    }

我收到的输出截图是:

我想在结构良好的 JSON 文件中获取输出,并且只需要其中的站名、到达时间和出发时间。请告诉我怎么做?

【问题讨论】:

  • railenquiry.in/runningstatus 是网页...它不返回 json?
  • 为了“读取” JSON,您请求的 URL 必须返回 json - 这只是一个普通的网页。您需要抓取返回的 html

标签: c# asp.net json httprequest


【解决方案1】:

看看这个项目:HtmlAgilityPack 但是你需要在使用他的数据之前询问网站所有者

【讨论】:

    【解决方案2】:

    您请求的 URL 只是一个普通网页,它不会返回 JSON。

    你需要抓取响应,才能做你想做的事。

    查看这个问题以获取使用 HtmlAgilityPack 的示例:

    Parsing HTML Table in C#

    【讨论】:

    • 你能告诉我如何读取我需要的数据,然后将其导出为 JSON 文件吗?
    • 查看示例链接 - 我们不是来为您工作的!
    • @sikrigagan 获取数据没有简单的规则。每个页面都有自己的规则。你应该阅读一些文件.....
    猜你喜欢
    • 2017-11-03
    • 1970-01-01
    • 2016-03-10
    • 2020-02-12
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多