将Tr064请求发送到AVM FritzBox 7270

时间:2017-01-17 11:20:54

标签: c# soap upnp fritzbox

我正在学习如何使用C#向我的AVM FritzBox 7270路由器发送SOAP请求。

这是我向路由器发送SOAP请求的方法:

    private string Execute(string controlUrl, string serviceType, string action)
    {
        WebRequest webRequest = WebRequest.Create("http://fritz.box:49000" + controlUrl);
        HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
        httpRequest.Method = "POST";
        httpRequest.ContentType = "text/xml; charset=utf-8";
        httpRequest.Headers.Add("SOAPACTION", string.Format("{0}#{1}", serviceType, action));
        httpRequest.ProtocolVersion = HttpVersion.Version11;
        httpRequest.Credentials = new NetworkCredential("username", "password"); 
        Stream requestStream = httpRequest.GetRequestStream();

        StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

        streamWriter.Write(GetBody(serviceType, action));
        streamWriter.Close();
        //Get the Response    
        try
        {
            HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
            StreamReader srd = new StreamReader(wr.GetResponseStream());
            return srd.ReadToEnd();
        }
        catch (WebException)
        {
            return null;
        }
    }

功能GetBody:

    private string GetBody(string serviceType, string action)
    {
        const string fmt = @"<?xml version=""1.0"" encoding=""utf-8""?>
<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"" s:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
  <s:Body>
    <u:{0} xmlns:u=""{1}"" />
  </s:Body>
</s:Envelope>
";        
            return string.Format(fmt, action, serviceType);
        }
    }

我使用我在互联网上的任何地方找到的参数测试了这个方法:

controlUrl = "/upnp/control/WANIPConn1"
serviceType = "urn:schemas-upnp-org:service:WANIPConnection:1"
action = "GetExternalIPAddress"

这很有效。

但是,我认为我应该采用正式方式并首先发送请求

http://fritz.box:49000/tr64desc.xml

接收对我的实际路由器有效的参数。在对此请求的响应中,我找到以下节点:

<service>
  <serviceType>urn:dslforum-org:service:WANIPConnection:1</serviceType>
  <serviceId>urn:WANIPConnection-com:serviceId:WANIPConnection1</serviceId>
  <controlURL>/upnp/control/wanipconnection1</controlURL>
  <eventSubURL>/upnp/control/wanipconnection1</eventSubURL>
  <SCPDURL>/wanipconnSCPD.xml</SCPDURL>
</service>

将这些值用于serviceId和controlUrl,我收到错误500(内部服务器错误)。

谁能帮帮我?我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

我认为问题已经解决了:

Fritz.Box似乎有很多未经证实的功能,我在互联网上发现的参数很明显是这些功能的一部分。

<service>
  <serviceType>urn:dslforum-org:service:WANPPPConnection:1</serviceType>
  <serviceId>urn:WANPPPConnection-com:serviceId:WANPPPConnection1</serviceId>
  <controlURL>/upnp/control/wanpppconn1</controlURL>
  <eventSubURL>/upnp/control/wanpppconn1</eventSubURL>
  <SCPDURL>/wanpppconnSCPD.xml</SCPDURL>
</service>

我可以打电话

GetExternalIPAddress

没问题。