Ejemplo n.º 1
0
        public static bool SendPingback(Uri source, Uri target, Uri pingbackUri, Action<string> logError, out int errorCode, out string serverMessage)
        {
            HttpRequestUtil http = new HttpRequestUtil(pingbackUri);

            string xmlrpc = @"<?xml version=""1.0""?><methodCall><methodName>pingback.ping</methodName><params>" +
                            @"<param><value><string>{0}</string></value></param>" +
                            @"<param><value><string>{1}</string></value></param></params></methodCall>";

            xmlrpc = String.Format(xmlrpc, HttpUtility.HtmlEncode(source.AbsoluteUri), HttpUtility.HtmlEncode(target.AbsoluteUri));
            byte[] postdata = Encoding.UTF8.GetBytes(xmlrpc);

            if (http.Post(pingbackUri.PathAndQuery, "application/xml", postdata, postdata.Length) != HttpStatusCode.OK)
            {
                logError(String.Format("POST {0}: {1}/{2}", pingbackUri, (int)http.StatusCode, http.StatusCode));
                errorCode = (int)http.StatusCode;
                serverMessage = "The server returned an http error " + (int)http.StatusCode;
            }
            else
            {
                if (!http.ContentType.StartsWith("text/xml", StringComparison.OrdinalIgnoreCase) &&
                    !http.ContentType.StartsWith("application/xml", StringComparison.OrdinalIgnoreCase))
                {
                    logError("Expected content type: application/xml, found: " + http.ContentType);
                }

                try
                {
                    XmlLightDocument doc = new XmlLightDocument(Encoding.UTF8.GetString(http.Content));

                    XmlLightElement error = doc.SelectSingleNode("methodResponse/fault");
                    if (error != null)
                    {
                        XmlLightElement faultCode = error.SelectSingleNode("value/struct/member[name/text()='faultCode']/value/int");
                        XmlLightElement faultString = error.SelectSingleNode("value/struct/member[name/text()='faultString']/value");
                        if (faultCode == null || !int.TryParse(faultCode.InnerText, out errorCode))
                            errorCode = 0;
                        serverMessage = faultString != null ? faultString.InnerText : "Unknown Error";
                    }
                    else
                    {
                        serverMessage = doc.SelectRequiredNode("/methodResponse/params/param/value").InnerText;
                        errorCode = 0;
                        return true;
                    }
                }
                catch (Exception e)
                {
                    logError("Error parsing response: " + e.Message);
                    serverMessage = "Unable to parse xml response.";
                    errorCode = 0;
                }
            }
            return false;
        }