繁体   English   中英

Unity HttpWebRequest 响应显示为 HTML 而不是 XML

[英]Unity HttpWebRequest response shows as HTML instead of XML

我正在尝试使用 HttpWebRequest WebRequest 从 Unity 发出 POST 请求,我只得到 HTML 代码,而在 Postman 中我得到了正确的结果。

我尝试过将 HttpWebRequest 与 StreamWriter 一起使用,我尝试以正常方式和异步方式进行操作。

我使用的 function

    public void GetResults()
    {
        byte[] bytes;
        bytes = Encoding.ASCII.GetBytes("<?xml version=\"1.0\" encoding=\"UTF - 8\"?><blabla>asdasd</blabla> ");
        string str = "[MY_API]";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(str);
        req.Method = "POST";
        req.ContentType = "text/xml";
        string strRequest = Encoding.ASCII.GetString(bytes);
        req.ContentLength = strRequest.Length;
        StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
        streamOut.Write(strRequest);
        streamOut.Close();
        StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
        string strResponse = streamIn.ReadToEnd();
        print(strResponse);
        streamIn.Close();

    }

预期的打印是带有一些数据的 XML 代码,但实际打印是

<html>
<body>
<h1>
200
</h1>
</body>
</html>

您需要指定接受类型:

req.Accept="application/xml" //or */*

我用过 Unity3dAzure 开源很棒的 package,RESTClient 它解决了我所有的问题。 非常容易使用。

https://github.com/Unity3dAzure/RESTClient

Note: It looks like for XML what I'm doing is not enough, this package handles XMl and JSON in a good way.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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