Exemplo n.º 1
0
        public override void Invoke(AMFContext context)
        {
            AMFDeserializer deserializer = new AMFDeserializer(context.InputStream);

            deserializer.UseLegacyCollection = _useLegacyCollection;
            try
            {
                AMFMessage amfMessage = deserializer.ReadAMFMessage();
                context.AMFMessage    = amfMessage;
                context.MessageOutput = new MessageOutput(amfMessage.Version);
                if (deserializer.FailedAMFBodies.Length > 0)
                {
                    AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies;
                    //Write out failed AMFBodies
                    for (int i = 0; i < failedAMFBodies.Length; i++)
                    {
                        context.MessageOutput.AddBody(failedAMFBodies[i]);
                    }
                }
            }
            catch
            {
                Dump(context.InputStream);
                throw;
            }
        }
Exemplo n.º 2
0
        private static DsoChatPacket TryParseAmf(string rawXmlData, byte[] rawData)
        {
            if (rawXmlData.Contains(@"/onResult") == false || rawXmlData.Contains("\r\n\r\n") == false)
            {
                return(null);
            }

            // Skip after \r\n\r\n
            int p       = rawXmlData.IndexOf("\r\n\r\n");
            var amfBody = rawXmlData.Substring(p + 4);

            // Next \r\n denotes AMF start, i thinnk..
            if (amfBody.Contains("\r\n"))
            {
                p       = amfBody.IndexOf("\r\n");
                amfBody = amfBody.Substring(p + 2);
            }
            var amfRawBody = TextEncoding.GetBytes(amfBody);

            using (var stream = new MemoryStream(amfRawBody)) {
                var deserializer = new AMFDeserializer(stream);
                var message      = deserializer.ReadAMFMessage();
            }

            return(null);
        }
Exemplo n.º 3
0
            /// <summary>
            /// One of the two main entry points into the encoder. Called by WCF to decode a buffered byte array into a message.
            /// </summary>
            /// <param name="buffer">A <see cref="T:System.ArraySegment`1"/> of type <see cref="T:System.Byte"/> that provides the buffer from which the message is deserialized.</param>
            /// <param name="bufferManager">The <see cref="T:System.ServiceModel.Channels.BufferManager"/> that manages the buffer from which the message is deserialized.</param>
            /// <param name="contentType">The Multipurpose Internet Mail Extensions (MIME) message-level content-type.</param>
            /// <returns>
            /// The <see cref="T:System.ServiceModel.Channels.Message"/> that is read from the stream specified.
            /// </returns>
            public override Message ReadMessage(ArraySegment <byte> buffer, BufferManager bufferManager, string contentType)
            {
                MemoryStream    memoryStream    = new MemoryStream(buffer.Array, buffer.Offset, buffer.Count - buffer.Offset);
                AMFDeserializer amfDeserializer = new AMFDeserializer(memoryStream);
                AMFMessage      amfMessage      = amfDeserializer.ReadAMFMessage();
                Message         returnMessage   = Message.CreateMessage(MessageVersion.None, null);

                returnMessage.Properties.Add("amf", amfMessage);
                return(returnMessage);
            }
Exemplo n.º 4
0
 /// <summary>
 /// 解析响应报文,把报文内容以amf对象的形式返回
 /// </summary>
 /// <param name="response">响应报文</param>
 /// <returns>返回amf信息对象</returns>
 public static AMFMessage GetAMFMessage(this WebResponse response)
 {
     using (Stream Stream = response.GetResponseStream())
     {
         using (AMFDeserializer AMFDeserializer = new AMFDeserializer(Stream))
         {
             return(AMFDeserializer.ReadAMFMessage());
         }
     }
 }
Exemplo n.º 5
0
 /// <summary>
 /// 解析响应报文,把报文内容以字符串的形式返回
 /// </summary>
 /// <param name="response">响应报文</param>
 /// <returns>返回报文内容字符串</returns>
 public static string GetText(this WebResponse response)
 {
     using (Stream stream = response.GetResponseStream())
     {
         using (AMFDeserializer amfDeserializer = new AMFDeserializer(stream))
         {
             AcknowledgeMessage msg = (AcknowledgeMessage)amfDeserializer.ReadAMFMessage().Bodies[0].Content;
             return(Convert.ToString(msg.body));
         }
     }
 }
Exemplo n.º 6
0
 private void BeginResponseFlashCall(IAsyncResult ar)
 {
     try
     {
         RequestData asyncState = ar.AsyncState as RequestData;
         if (asyncState != null)
         {
             HttpWebResponse response = (HttpWebResponse)asyncState.Request.EndGetResponse(ar);
             if (response != null)
             {
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     AMFMessage message = new AMFDeserializer(responseStream).ReadAMFMessage();
                     AMFBody    bodyAt  = message.GetBodyAt(0);
                     for (int i = 0; i < message.HeaderCount; i++)
                     {
                         AMFHeader headerAt = message.GetHeaderAt(i);
                         if (headerAt.Name == "RequestPersistentHeader")
                         {
                             this._netConnection.AddHeader(headerAt.Name, headerAt.MustUnderstand, headerAt.Content);
                         }
                     }
                     PendingCall call = asyncState.Call;
                     call.Result = bodyAt.Content;
                     if (bodyAt.Target.EndsWith("/onStatus"))
                     {
                         call.Status = 0x13;
                     }
                     else
                     {
                         call.Status = 2;
                     }
                     asyncState.Callback.ResultReceived(call);
                 }
                 else
                 {
                     this._netConnection.RaiseNetStatus("Could not aquire ResponseStream");
                 }
             }
             else
             {
                 this._netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
             }
         }
     }
     catch (Exception exception)
     {
         this._netConnection.RaiseNetStatus(exception);
     }
 }
Exemplo n.º 7
0
        private AMFObject GetResponse(string url, byte[] postData)
        {
            //Log.Debug("get webdata from {0}", url);

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            if (request == null)
            {
                return(null);
            }
            request.Method          = "POST";
            request.ContentType     = "application/x-amf";
            request.UserAgent       = OnlineVideoSettings.Instance.UserAgent;
            request.Referer         = "http://admin.brightcove.com/viewer/us20111122.1604/federatedVideoUI/BrightcovePlayer.swf";
            request.Timeout         = 15000;
            request.ContentLength   = postData.Length;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

            System.Net.WebProxy proxy = getProxy();
            if (proxy != null)
            {
                request.Proxy = proxy;
            }

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Stream responseStream;
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                {
                    responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                else if (response.ContentEncoding.ToLower().Contains("deflate"))
                {
                    responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                else
                {
                    responseStream = response.GetResponseStream();
                }

                AMFDeserializer des = new AMFDeserializer(responseStream);
                AMFObject       obj = des.Deserialize();
                return(obj);
            }
        }
Exemplo n.º 8
0
        private void parse(string amf, string name)
        {
            byte[] bbb = StrToToHexByte(amf);

            AMFDeserializer ad      = new AMFDeserializer(new MemoryStream(bbb));
            AMFMessage      message = ad.ReadAMFMessage();

            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(message);

            //Write that JSON to txt file
            File.WriteAllText(@"z:\temp\hotel\" + name + @".json", json);

            foreach (var body in message.Bodies)
            {
                object[]        content = body.Content as object[];
                RemotingMessage rm      = content[0] as RemotingMessage;

                rm.messageId = Guid.NewGuid().ToString("D");

                object[] bodys = rm.body as object[];
                ASObject ab    = bodys[2] as ASObject;

                ASObject masterBase = ab["masterBase"] as ASObject;
                masterBase["dep"]        = DateTime.Now;
                masterBase["arr"]        = DateTime.Now;
                masterBase["rsvMan"]     = "马一一";
                masterBase["cutoffDate"] = DateTime.Now;

                ASObject masterGuest = ab["masterGuest"] as ASObject;
                masterGuest["name"]  = "马一一";
                masterGuest["name2"] = "Ma Yi Yi";
                masterGuest["sex"]   = "1";

                ArrayCollection rsvSrcList = ab["rsvSrcList"] as ArrayCollection;
                ASObject        rsvObject  = rsvSrcList[0] as ASObject;
                rsvObject["arrDate"]    = DateTime.Now;
                rsvObject["depDate"]    = DateTime.Now;
                rsvObject["rsvArrDate"] = DateTime.Now;
                rsvObject["rsvDepDate"] = DateTime.Now;
                rsvObject["negoRate"]   = 268;
                rsvObject["oldRate"]    = 268;
                rsvObject["realRate"]   = 268;
                rsvObject["rackRate"]   = 268;
            }
        }
Exemplo n.º 9
0
		public override void Invoke(AMFContext context) {
			AMFDeserializer deserializer = new AMFDeserializer(context.InputStream);
			deserializer.UseLegacyCollection = _useLegacyCollection;
			try {
				AMFMessage amfMessage = deserializer.ReadAMFMessage();
				context.AMFMessage = amfMessage;
				context.MessageOutput = new MessageOutput(amfMessage.Version);
				if (deserializer.FailedAMFBodies.Length > 0) {
					AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies;
					//Write out failed AMFBodies
					for (int i = 0; i < failedAMFBodies.Length; i++)
						context.MessageOutput.AddBody(failedAMFBodies[i]);
				}
			} catch {
				Dump(context.InputStream);
				throw;
			}
		}
Exemplo n.º 10
0
        /// <summary>
        /// 获取当前的村委会清单
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="responseNo"></param>
        /// <returns></returns>
        public DataSet GetSysCommittee(string cookie, string responseNo)
        {
            DataSet dtUploadSetRow = new DataSet();

            ManagerBase mb = new ManagerBase(SendType.Query);

            byte[] byteSend = GetNode(responseNo);

            string sendHeader = CommonExtensions.GetSendHeader(cookie, byteSend.Length).ToString();

            mb.SendMessage(cookie, byteSend, sendHeader);

            AMFDeserializer ad          = new AMFDeserializer(new MemoryStream(mb.socketReceiveData));
            AMFMessage      timeMessage = ad.ReadAMFMessage();

            mb.socketReceiveData = null;

            if (timeMessage.BodyCount == 0 || timeMessage.Bodies.FirstOrDefault().Content is FluorineFx.Messaging.Messages.ErrorMessage)
            {
                CommonExtensions.WriteLog("不存在");

                return(dtUploadSetRow);
            }

            var content = (AcknowledgeMessage)timeMessage.Bodies.FirstOrDefault().Content;

            // node 字符串

            /*
             * <node id='3064' name='中亚南路街道办事处' level='4' levelCN='乡镇' code='650104014' isLoad='true' isBranch='true'>
             *  <node id='3718' name='团结新村社区居委会' level='5' levelCN='村' code='650104014007' isLoad='false' ></node>
             *  <node id='3721' name='铁路花园社区居委会' level='5' levelCN='村' code='650104014010' isLoad='false' ></node>
             * </node>
             */
            var strNodes = content.body.ToString();


            using (StringReader xmlSR = new StringReader(strNodes))
            {
                dtUploadSetRow.ReadXml(xmlSR);
            }

            return(dtUploadSetRow);
        }
Exemplo n.º 11
0
        public override void Invoke(AMFContext context)
        {
            AMFDeserializer deserializer = new AMFDeserializer(context.InputStream)
            {
                UseLegacyCollection = this._useLegacyCollection
            };
            AMFMessage message = deserializer.ReadAMFMessage();

            context.AMFMessage    = message;
            context.MessageOutput = new MessageOutput(message.Version);
            if (deserializer.FailedAMFBodies.Length > 0)
            {
                AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies;
                for (int i = 0; i < failedAMFBodies.Length; i++)
                {
                    context.MessageOutput.AddBody(failedAMFBodies[i]);
                }
            }
        }
Exemplo n.º 12
0
        public override Task Invoke(AMFContext context)
        {
            AMFDeserializer deserializer = new AMFDeserializer(context.InputStream);

            deserializer.UseLegacyCollection = _useLegacyCollection;
            AMFMessage amfMessage = deserializer.ReadAMFMessage();

            context.AMFMessage    = amfMessage;
            context.MessageOutput = new MessageOutput(amfMessage.Version);
            if (deserializer.FailedAMFBodies.Length > 0)
            {
                AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies;
                //Write out failed AMFBodies
                for (int i = 0; i < failedAMFBodies.Length; i++)
                {
                    context.MessageOutput.AddBody(failedAMFBodies[i]);
                }
            }
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 13
0
        private AMFMessage LoadBinMessageIntoAmfMessage(byte[] encodedMessage)
        {
            AMFMessage message = null;

            byte[]       buffer = encodedMessage;
            MemoryStream stream = new MemoryStream(buffer);

            try
            {
                message = new AMFDeserializer(stream).ReadAMFMessage();
            }
            catch (DecoderFallbackException)
            {
                stream.Position = 0;
                object content = new AMFReader(stream)
                {
                    FaultTolerancy = true
                }.ReadAMF3Data();
                message = new AMFMessage(3);
                message.AddBody(new AMFBody(string.Empty, string.Empty, content));
            }

            return(message);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Десериализует буфер данных в объект AMF.
        /// </summary>
        /// <typeparam name="T">Тип десериализуемого объекта.</typeparam>
        /// <param name="sourceBuffer">Исходный буфер данных объекта.</param>
        /// <returns></returns>
        public static T DeserializeFromAmf <T>(this byte[] sourceBuffer) where T : class
        {
            using (MemoryStream memoryStream = new MemoryStream(sourceBuffer))              // Открываем поток для чтения данных из буфера.
                using (AMFDeserializer amfDeserializer = new AMFDeserializer(memoryStream)) // Инициализируем десериализатор для AMF.
                {
                    AMFMessage amfMessage = amfDeserializer.ReadAMFMessage();               // Получем сообщение AMF.
                    AMFBody    amfBody    = amfMessage.GetBodyAt(0);                        // Получаем body из сообщения AMF.

                    object amfObject     = amfBody.Content;                                 // Получаем объект из body AMF.
                    Type   amfObjectType = amfObject.GetType();                             // Получаем метаданные типа объекта AMF.

                    // Формируем запрос на получение всей коллекции нужных нам типов с заданными атрибутами.
                    IEnumerable <Type> types = from type in Assembly.GetExecutingAssembly().GetTypes()
                                               where Attribute.IsDefined(type, typeof(AmfObjectAttribute))
                                               select type;

                    Type currentType = null; // Определяем текущий тип объекта из нашей сборки.

                    // Проходим по всем найденным типам с нашим атрибутом.
                    foreach (Type type in types)
                    {
                        AmfObjectAttribute attribute = type.GetAttribute <AmfObjectAttribute>(); // Получаем наш атрибут.

                        if (attribute == null || attribute.Name != amfObjectType.FullName)
                        {
                            continue;       // Если в атрибуте задано другое имя - пропускаем итерацию.
                        }
                        currentType = type; // Иначе сохраняем текущий тип объекта.
                        break;
                    }

                    if (currentType == null)
                    {
                        return(default(T));                                      // Если тип не найден - возвращаем null.
                    }
                    object targetObject = Activator.CreateInstance(currentType); // Создаём инстанс нашего типа.

                    // Анализируем все свойства нашего класса.
                    foreach (PropertyInfo propertyInfo in currentType.GetProperties())
                    {
                        AmfMemberAttribute attribute = propertyInfo.GetAttribute <AmfMemberAttribute>(); // Получаем наш кастомный атрибут.

                        if (attribute == null)
                        {
                            continue;                                                                                                   // Если атрибут не задан - пропускаем.
                        }
                        propertyInfo.SetValue(targetObject, amfObjectType.GetProperty(attribute.Name).GetValue(amfObject, null), null); // Получаем значение свойства у десериализуемого объекта и сохраняем его в свойстве нашего объекта.
                    }

                    // Анализируем все поля нашего класса.
                    foreach (FieldInfo fieldInfo in currentType.GetFields())
                    {
                        AmfMemberAttribute attribute = fieldInfo.GetAttribute <AmfMemberAttribute>(); // Получаем наш кастомный атрибут.

                        if (attribute == null)
                        {
                            continue;                                                                                 // Если атрибут не задан - пропускаем.
                        }
                        fieldInfo.SetValue(targetObject, amfObjectType.GetField(attribute.Name).GetValue(amfObject)); // Получаем значение поля у десериализуемого объекта и сохраняем его в поле нашего объекта.
                    }

                    return(targetObject as T); // Приводит к типу T и возвращает текущий объект.
                }
        }
Exemplo n.º 15
0
 private void BeginResponseFlexCall(IAsyncResult ar)
 {
     try
     {
         AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData;
         if (amfRequestData != null)
         {
             HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar);
             if (response != null)
             {
                 //Get response and deserialize
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream);
                     AMFMessage responseMessage = amfDeserializer.ReadAMFMessage();
                     AMFBody responseBody = responseMessage.GetBodyAt(0);
                     for (int i = 0; i < responseMessage.HeaderCount; i++)
                     {
                         AMFHeader header = responseMessage.GetHeaderAt(i);
                         if (header.Name == AMFHeader.RequestPersistentHeader)
                             _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content);
                     }
                     object message = responseBody.Content;
                     if (message is ErrorMessage)
                     {
                         /*
                         ASObject status = new ASObject();
                         status["level"] = "error";
                         status["code"] = "NetConnection.Call.Failed";
                         status["description"] = (result as ErrorMessage).faultString;
                         status["details"] = result;
                         _netConnection.RaiseNetStatus(status);
                         */
                         if (amfRequestData.Call != null)
                         {
                             PendingCall call = amfRequestData.Call;
                             call.Result = message;
                             call.Status = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION;
                             amfRequestData.Callback.ResultReceived(call);
                         }
                         if (amfRequestData.Responder != null)
                         {
                             StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction;
                             if (statusFunction != null)
                                 statusFunction(new Fault(message as ErrorMessage));
                         }
                     }
                     else if (message is AcknowledgeMessage)
                     {
                         AcknowledgeMessage ack = message as AcknowledgeMessage;
                         if (_netConnection.ClientId == null && ack.HeaderExists(MessageBase.FlexClientIdHeader))
                             _netConnection.SetClientId(ack.GetHeader(MessageBase.FlexClientIdHeader) as string);
                         if (amfRequestData.Call != null)
                         {
                             PendingCall call = amfRequestData.Call;
                             call.Result = ack.body;
                             call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                             amfRequestData.Callback.ResultReceived(call);
                         }
                         if (amfRequestData.Responder != null)
                         {
                             Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate;
                             if (resultFunction != null)
                             {
                                 ParameterInfo[] arguments = resultFunction.Method.GetParameters();
                                 object result = TypeHelper.ChangeType(ack.body, arguments[0].ParameterType);
                                 resultFunction.DynamicInvoke(result);
                             }
                         }
                     }
                 }
                 else
                     _netConnection.RaiseNetStatus("Could not aquire ResponseStream");
             }
             else
                 _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
         }
     }
     catch (Exception ex)
     {
         _netConnection.RaiseNetStatus(ex);
     }
 }
Exemplo n.º 16
0
 private void BeginResponseFlashCall(IAsyncResult ar)
 {
     try
     {
         AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData;
         if (amfRequestData != null)
         {
             HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar);
             if (response != null)
             {
                 //Get response and deserialize
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream);
                     AMFMessage responseMessage = amfDeserializer.ReadAMFMessage();
                     AMFBody responseBody = responseMessage.GetBodyAt(0);
                     for (int i = 0; i < responseMessage.HeaderCount; i++)
                     {
                         AMFHeader header = responseMessage.GetHeaderAt(i);
                         if (header.Name == AMFHeader.RequestPersistentHeader)
                             _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content);
                     }
                     if (amfRequestData.Call != null)
                     {
                         PendingCall call = amfRequestData.Call;
                         call.Result = responseBody.Content;
                         call.Status = responseBody.Target.EndsWith(AMFBody.OnStatus) ? Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION : Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                         amfRequestData.Callback.ResultReceived(call);
                     }
                     if (amfRequestData.Responder != null)
                     {
                         if (responseBody.Target.EndsWith(AMFBody.OnStatus))
                         {
                             StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction;
                             if (statusFunction != null)
                                 statusFunction(new Fault(responseBody.Content));
                         }
                         else
                         {
                             Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate;
                             if (resultFunction != null)
                             {
                                 ParameterInfo[] arguments = resultFunction.Method.GetParameters();
                                 object result = TypeHelper.ChangeType(responseBody.Content, arguments[0].ParameterType);
                                 resultFunction.DynamicInvoke(result);
                             }
                         }
                     }
                 }
                 else
                     _netConnection.RaiseNetStatus("Could not aquire ResponseStream");
             }
             else
                 _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
         }
     }
     catch (Exception ex)
     {
         _netConnection.RaiseNetStatus(ex);
     }
 }
Exemplo n.º 17
0
		private static DsoChatPacket TryParseAmf(string rawXmlData, byte[] rawData) {
			if (rawXmlData.Contains(@"/onResult") == false || rawXmlData.Contains("\r\n\r\n") == false) {
				return null;
			}

			// Skip after \r\n\r\n
			int p = rawXmlData.IndexOf("\r\n\r\n");
			var amfBody = rawXmlData.Substring(p + 4);
			// Next \r\n denotes AMF start, i thinnk..
			if (amfBody.Contains("\r\n")) {
				p = amfBody.IndexOf("\r\n");
				amfBody = amfBody.Substring(p + 2);
			}
			var amfRawBody = TextEncoding.GetBytes(amfBody);
			
			using (var stream = new MemoryStream(amfRawBody)) {
				var deserializer = new AMFDeserializer(stream);
				var message = deserializer.ReadAMFMessage();
			}

			return null;
		}
Exemplo n.º 18
0
 private void BeginResponseFlexCall(IAsyncResult ar)
 {
     try
     {
         RequestData asyncState = ar.AsyncState as RequestData;
         if (asyncState != null)
         {
             HttpWebResponse response = (HttpWebResponse)asyncState.Request.EndGetResponse(ar);
             if (response != null)
             {
                 Stream responseStream = response.GetResponseStream();
                 if (responseStream != null)
                 {
                     PendingCall call;
                     AMFMessage  message = new AMFDeserializer(responseStream).ReadAMFMessage();
                     AMFBody     bodyAt  = message.GetBodyAt(0);
                     for (int i = 0; i < message.HeaderCount; i++)
                     {
                         AMFHeader headerAt = message.GetHeaderAt(i);
                         if (headerAt.Name == "RequestPersistentHeader")
                         {
                             this._netConnection.AddHeader(headerAt.Name, headerAt.MustUnderstand, headerAt.Content);
                         }
                     }
                     object content = bodyAt.Content;
                     if (content is ErrorMessage)
                     {
                         call        = asyncState.Call;
                         call.Result = content;
                         call.Status = 0x13;
                         asyncState.Callback.ResultReceived(call);
                     }
                     if (content is AcknowledgeMessage)
                     {
                         AcknowledgeMessage message2 = content as AcknowledgeMessage;
                         if ((this._netConnection.ClientId == null) && message2.HeaderExists("DSId"))
                         {
                             this._netConnection.SetClientId(message2.GetHeader("DSId") as string);
                         }
                         call        = asyncState.Call;
                         call.Result = message2.body;
                         call.Status = 2;
                         asyncState.Callback.ResultReceived(call);
                     }
                 }
                 else
                 {
                     this._netConnection.RaiseNetStatus("Could not aquire ResponseStream");
                 }
             }
             else
             {
                 this._netConnection.RaiseNetStatus("Could not aquire HttpWebResponse");
             }
         }
     }
     catch (Exception exception)
     {
         this._netConnection.RaiseNetStatus(exception);
     }
 }
Exemplo n.º 19
0
        private AMFObject GetResponse(string url, byte[] postData)
        {
            //Log.Debug("get webdata from {0}", url);

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            if (request == null) return null;
            request.Method = "POST";
            request.ContentType = "application/x-amf";
            request.UserAgent = OnlineVideoSettings.Instance.UserAgent;
            request.Referer = "http://admin.brightcove.com/viewer/us20111122.1604/federatedVideoUI/BrightcovePlayer.swf";
            request.Timeout = 15000;
            request.ContentLength = postData.Length;
            request.ProtocolVersion = HttpVersion.Version10;
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

            System.Net.WebProxy proxy = getProxy();
            if (proxy != null)
                request.Proxy = proxy;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Stream responseStream;
                if (response.ContentEncoding.ToLower().Contains("gzip"))
                    responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                else if (response.ContentEncoding.ToLower().Contains("deflate"))
                    responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                else
                    responseStream = response.GetResponseStream();

                AMFDeserializer des = new AMFDeserializer(responseStream);
                AMFObject obj = des.Deserialize();
                return obj;
            }

        }