使用CefSharp从localhost端口获取数据的方法

时间:2015-11-03 01:16:59

标签: javascript c# jquery html cefsharp

目前正在开发一个显示Web浏览器的.net C#应用程序。但是由于visual studio web浏览器仍在使用ie7并且不支持很多东西,我计划将CefSharp放入Chromium。那么,你们每次尝试使用CefSharp从localhost服务器获取一些json数据吗?我尝试了两种方法但却失败了。

对于Visual Studio中的C#,我解雇了Chromium浏览器:

var test = new CefSharp.WinForms.ChromiumWebBrowser(AppDomain.CurrentDomain.BaseDirectory + "html\\index.html")
        {
            Dock = DockStyle.Fill,
        };
        this.Controls.Add(test);

然后对于index.html,需要在加载后从本地主机端口1000获取数据。我已经尝试了两种方式来使用javascript:

首先使用XMLHttpRequest:

var xmlhttp = new XMLHttpRequest();
  var url = "http://localhost:1000/api/data1";
  var services;
  xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          services = jQuery.parseJSON(xmlhttp.responseText);
      }
  }
  xmlhttp.open("GET", url, true);
  xmlhttp.send();

其次使用jquery' s .get():

      $.get("http://localhost:1000/api/data1", function (data) {
      var services = data;
  });

但两种方式都无法返回数据。如果我将index.html放入Chrome或Firefox等普通浏览器中,我就可以获取数据。

我的编码中缺少什么?任何想法是什么错误的人?

1 个答案:

答案 0 :(得分:0)

我正在使用Chromium Web浏览器并向localhost发出GET请求以获取JSON。除此之外,我正在运行一个继续监听并返回JSON的网络服务器。

网络服务器:

public class WebServer
{
    public WebServer()
    {
    }
    void Process(object o)
    {
        Thread thread = new Thread(() => new WebServer().Start());
        thread.Start();

        HttpListenerContext context = o as HttpListenerContext;
        HttpListenerResponse response = context.Response;
        try
        {
            string json;
            string url = context.Request.Url.ToString();
            if (url.Contains("http://localhost:8888/json"))
            {
                List<SampleObject> list = new List<SampleObject>();
                json = JsonConvert.SerializeObject(new
                {
                    results = list
                });
                byte[] decryptedbytes = new byte[0];
                decryptedbytes = System.Text.Encoding.UTF8.GetBytes(json);
                response.AddHeader("Content-type", "text/json");
                response.ContentLength64 = decryptedbytes.Length;
                System.IO.Stream output = response.OutputStream;
                try
                {
                    output.Write(decryptedbytes, 0, decryptedbytes.Length);
                    output.Close();
                }
                catch (Exception e)
                {
                    response.StatusCode = 500;
                    response.StatusDescription = "Server Internal Error";
                    response.Close();
                    Console.WriteLine(e.Message);
                }
            }
        }
        catch (Exception ex)
        {
            response.StatusCode = 500;
            response.StatusDescription = "Server Internal Error";
            response.Close();
            Console.WriteLine(ex);
        }
    }
    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
    public void Start()
    {
        HttpListener server = new HttpListener();
        server.Prefixes.Add("http://localhost:8888/json");
        server.Start();
        while (true)
        {
            ThreadPool.QueueUserWorkItem(Process, server.GetContext());  
        }

    }
}
public class SampleObject
{
    string param1 { get; set; }
    string param2 { get; set; }
    string param3 { get; set; }
}

启动网络服务器:

Thread thread = new Thread(() => new WebServer().Start());
        thread.Start();

的index.html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $.get("http://localhost:8888/json", function (data) {
      var jsonData= data;
  });
});
</script>
</head>
<body>

<p>Example JSON Request.</p>

</body>
</html>

在Chromium Web浏览器中启动Index.html之前,请开始运行webserver以侦听请求。在文档加载事件之后,它进行ajax调用,然后它命中Webserver,然后Webserver返回JSON。您也可以使用Chrome进行测试。启动网络服务器并在地址栏中输入URL(the docs),您将在开发人员工具中看到返回的JSON。

注意:代码未经过测试。希望它能奏效。