首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法从InputStream读取HttpListenerRequest

无法从InputStream读取HttpListenerRequest
EN

Stack Overflow用户
提问于 2015-06-20 00:54:01
回答 1查看 98关注 0票数 0

我一直在创建下载管理器,接收文件名,并从chrome扩展名下载链接。

在本例中,我决定使用javascript背景页发送XMLHttpRequest回送,并创建简单的服务器来接收消息,后台页面如下所示。

background.js

代码语言:javascript
复制
function showMessageBox(info, tab) {
    var link = decodeURIComponent(info.linkUrl);
    var index = link.search(/[^/\\\?]+\.\w{3,4}(?=([\?&].*$|$))/);
    var fileName = link.substring(index);
    alert("will download from " + link + " soon\n File name : " + fileName);
    SendMessage(fileName,link);
}
function SendMessage(fileName, link) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST","http://localhost:6230", false);
    xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    var JSONstring = JSON.stringify({ FileName: fileName, DownloadLink: link });
    xhr.send(JSONstring);
}

以及服务器的部分。

代码语言:javascript
复制
    private void StartReciever()
    {
        while (true)
        {
            var fileInfo = GetFileInfo();
            Execute.OnUIThread(() => WindowManager.ShowDialog(
                new NewDownloadViewModel(WindowManager, EventAggregator, fileInfo, Engine)));
        }
    }

    private FileInfo GetFileInfo()
    {
        using (var listener = new HttpListener())
        {
            listener.Prefixes.Add("http://localhost:6230/");
            listener.Start();
            var requestContext = listener.GetContext();
            /*var streamReader = new StreamReader(requestContext.Request.InputStream, requestContext.Request.ContentEncoding);
            string jsonString = streamReader.ReadToEnd();*/
            var stream = requestContext.Request.InputStream;
            byte[] buffer = new byte[10240];
            var readbyte = stream.Read(buffer, 0, 102400);
            string ss = Encoding.UTF8.GetString(buffer, 0, readbyte);
            // deserialize string to object

            return new FileInfo();
        }
    }

我想知道为什么流读取总是在发送消息时返回0。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-20 12:29:33

最后,我发现我忘记了什么!

根据同源政策的说法,我不能将http请求发送到不同来源的服务器。

我必须使用跨源XMLHttpRequest与不同来源的服务器通信。

要做到这一点,我需要通过将主机名添加到权限部分来请求跨源权限

就我而言我长得像这样。

代码语言:javascript
复制
"permissions": [
"contextMenus",
"http://localhost/",
"nativeMessaging"
]

现在,我可以接收字符串并反序列化它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30949212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档