使用CefSharp从本地主机端口获取数据的方法 [英] Ways to get data from localhost port using CefSharp
问题描述
对于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的.get():
$ .get(http:// localhost:1000 / api / data1,function(data){
var services = data;
});
但这两种方式都无法返回数据。如果我将index.html放入Chrome或Firefox这样的普通浏览器中,我就可以得到这些数据。
我的代码中是否缺少某些东西?任何想法什么是错的家伙?
我正在使用Chromium Web浏览器并向本地主机发送GET请求以获取JSON。随着这一点,我运行一个网络服务器,不断监听并返回JSON。
> public class WebServer
{
public WebServer()
{
}
进程(对象o)
{
Thread thread = new Thread(()=> new WebServer()。Start());
thread.Start();
HttpListenerContext context = o作为HttpListenerContext;
HttpListenerResponse response = context.Response;
尝试
{
字符串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;
尝试
{
output.Write(decryptedbytes,0,decryptedbytes.Length);
output.Close();
}
catch(Exception e)
{
response.StatusCode = 500;
response.StatusDescription =服务器内部错误;
response.Close();
Console.WriteLine(e.Message);
}
}
}
catch(Exception ex)
{
response.StatusCode = 500;
response.StatusDescription =服务器内部错误;
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);
返回字节;
}
public void Start()
{
HttpListener server = new HttpListener();
server.Prefixes.Add(http:// localhost:8888 / json);
server.Start();
while(true)
{
ThreadPool.QueueUserWorkItem(Process,server.GetContext());
}
}
}
公共类SampleObject
{
string param1 {get;组; }
string param2 {get;组; }
string param3 {get;组; }
}
启动网络服务器:
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;}); });< /脚本>< /头><主体>< p为H.;实施例JSON请求< / p>< / BODY>< / HTML>
$ 在Chromium网络浏览器中启动Index.html之前,开始运行webserver来侦听请求。在文档加载事件之后,它会进行ajax调用,然后它会点击Webserver,然后Webserver将返回JSON。你也可以使用Chrome来测试它。启动网络服务器并在地址栏中输入URL( http:// localhost:8888 / json ),您将看到返回的JSON在开发人员工具中。
注意:代码未经测试。希望它能起作用。
currently developing a .net C# application which is showing a web browser. But since visual studio web browser is still using ie7 and does not support quite lots of things, I plan to put in the CefSharp which is the Chromium. So, have you guys every try get some json data from a localhost server using CefSharp? I have tried two ways to get it but failed.
For C# in Visual Studio, I fired the Chromium browser like this:
var test = new CefSharp.WinForms.ChromiumWebBrowser(AppDomain.CurrentDomain.BaseDirectory + "html\\index.html")
{
Dock = DockStyle.Fill,
};
this.Controls.Add(test);
Then for the index.html, it is require to get data from local host port 1000 after it loaded. I have tried two ways for the javascript:
First using 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();
Secondly using jquery's .get():
$.get("http://localhost:1000/api/data1", function (data) {
var services = data;
});
But both ways can't return the data. If I put the index.html into normal browser like Chrome or Firefox, I am able to get the data.
Is it something missing in my coding? Any ideas what's wrong guys?
I am using Chromium web browser and making GET request to localhost for JSON. Along with this i am running a webserver which keeps on listening and return JSON.
Webserver:
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; }
}
To Start Webserver:
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>
Before launching Index.html inside Chromium web browser, start running webserver to listen for requests. After document load event it makes a ajax call, then it hits the Webserver then Webserver returns JSON. You can test it using Chrome also. Start webserver and type the URL(http://localhost:8888/json) in address bar you will see returned JSON in Developers tools.
Note: Code is not tested. Hope it will work.
这篇关于使用CefSharp从本地主机端口获取数据的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!