简体   繁体   中英

Cannot read InputStream from HttpListenerRequest

I've been creating download manager that receive file name and download link from chrome extension.
In this case I decided to use javascript background page to send XMLHttpRequest to loopback and create simple server to receive message the background page look like this.

background.js

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);
}

and the part of server.

    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();
        }
    }

I wonder why stream read always return 0 when message was sent.

Finally, I found what I forgot!

According to Same-origin policy , I can't send http request to server that isn't the same origin.
I must use Cross-Origin XMLHttpRequest to communicate to server that isn't the same origin.

To do that I need to Request cross-origin permissions by add hostname to permissions section.
In my case I look like this.

"permissions": [
"contextMenus",
"http://localhost/",
"nativeMessaging"
]

Now, I can receive string and deserialize it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM