Inheritance: System.Collections.Specialized.NameValueCollection
        public HttpResponseMessage GetHttpResponse(Uri uri, string method, WebHeaderCollection headers)
        {
            WebRequest request = WebRequest.Create(uri);
            request.Method = method;
            if (headers != null)
            {
                foreach (string name in headers)
                {
                    request.Headers.Add(name, headers[name]);
                }
            }

            using (WebResponse respFromServer = request.GetResponse())
            {
                using (Stream dataStream = respFromServer.GetResponseStream())
                {
                    MemoryStream ms = new MemoryStream();
                    dataStream.CopyTo(ms);

                    HttpResponseMessage response = new HttpResponseMessage();
                    response.StatusCode = HttpStatusCode.OK;
                    ms.Position = 0;
                    response.Content = new StreamContent(ms);
                    response.Content.Headers.Add("Content-Type", respFromServer.ContentType);

                    return response;
                }
            }
        }
 public async Task<SummaryTemperatureData> GetStdAsync()
 {
     // var uri = new Uri("http://jeffa.org:81/ha/SummaryData.php");
     //var uri = new Uri(App.SummaryDataUrl);
     //var client = new HttpClient();
     //var opContent = (await client.GetAsync(uri)).Content;
     //string foo = await opContent.ReadAsStringAsync();
     //var fooo = JsonConvert.DeserializeObjectAsync<SummaryTemperatureData>(foo);
     //return await fooo;
     var applicationDataSettingsService = new ApplicationDataSettingsService();
     try
     {
     // ToDo need to wrap this a bit. error checking. disposal....
     WebHeaderCollection headers = new WebHeaderCollection();
     WebRequest request = WebRequest.Create(new Uri(applicationDataSettingsService.SummaryDataUrl));
     request.ContentType = "application/xml";
     WebResponse response = await request.GetResponseAsync();
     // response.Close(); // ?? hmmm
     Debug.WriteLine("\nThe HttpHeaders are \n{0}", request.Headers);
     Stream inputStream = response.GetResponseStream();
     XmlReader xmlReader = XmlReader.Create(inputStream);
     XmlSerializer xml = new XmlSerializer(typeof(SummaryTemperatureData));
     var stdXml = (SummaryTemperatureData)xml.Deserialize(xmlReader);
     return stdXml;
     }
     catch (Exception e)
     {
         Utility.Log(this, e.ToString());
         return null;
     }
 }
Example #3
0
 protected WebResponse(HttpStatusCode statusCode, string content, string contentType)
 {
     StatusCode = statusCode;
     Content = content;
     ContentType = contentType;
     additionalHeaders = new WebHeaderCollection();
 }
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            HttpResponseMessageProperty responseProperties =
                (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];

            ResponseHeaders = responseProperties.Headers;
        }
Example #5
0
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="url">Url</param>
 /// <param name="headers">Http headers</param>
 /// <param name="status">Response status code</param>
 /// <param name="body">Response raw body</param>
 public HttpResponse(string url, WebHeaderCollection headers, int status, byte[] body)
 {
     Url = url;
     Headers = headers;
     Status = status;
     Body = body;
 }
        private static XmlDocument SimpleRequest(string method, ref Uri uri, HttpRequestFilter filter, out WebHeaderCollection responseHeaders, params string[] parameters)
        {
            string absUri = UrlHelper.SafeToAbsoluteUri(uri);

            if (parameters.Length > 0)
            {
                FormData formData = new FormData(true, parameters);

                if (absUri.IndexOf('?') == -1)
                    absUri += "?" + formData.ToString();
                else
                    absUri += "&" + formData.ToString();
            }

            RedirectHelper.SimpleRequest simpleRequest = new RedirectHelper.SimpleRequest(method, filter);
            HttpWebResponse response = RedirectHelper.GetResponse(absUri, new RedirectHelper.RequestFactory(simpleRequest.Create));
            try
            {
                uri = response.ResponseUri;
                responseHeaders = response.Headers;
                return ParseXmlResponse(response);
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
        }
Example #7
0
        private MFTestResults SetCommonHttpResponseHeaders_1_0(ref System.Net.WebHeaderCollection wrs)
        {
            MFTestResults result = MFTestResults.Pass;

            try
            {
                Log.Comment("Set Response Headers Properties");
                wrs.Set(HttpKnownHeaderNames.Allow.ToString(), "GET");
                wrs.Set(HttpKnownHeaderNames.ContentEncoding.ToString(), "gzip");
                wrs.Set(HttpKnownHeaderNames.ContentLength.ToString(), "26012");
                wrs.Set(HttpKnownHeaderNames.ContentType.ToString(), "text/plain, image/gif");
                wrs.Set(HttpKnownHeaderNames.Expires.ToString(), "Thu, 01 Dec 1994 16:00:00 GMT");  //always force client cache validate on the request
                wrs.Set(HttpKnownHeaderNames.KeepAlive.ToString(), "");
                wrs.Set(HttpKnownHeaderNames.LastModified.ToString(), "Fri, 22 May 2009 12:43:31 GMT");
                wrs.Set(HttpKnownHeaderNames.Location.ToString(), "http://www.w3.org/pub/WWW/People.html");
                wrs.Set(HttpKnownHeaderNames.WWWAuthenticate.ToString(), "BASIC realm=\"executives\"");
            }
            catch (Exception ex)
            {
                if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException)))
                {
                    result = MFTestResults.Fail;
                }
            }

            return(result);
        }
Example #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AirbrakeResponse"/> class.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="content">The content.</param>
        public AirbrakeResponse(WebResponse response, string content)
        {
            this.log = LogManager.GetLogger(GetType());
            this.content = content;
            this.errors = new AirbrakeResponseError[0];

            if (response != null)
            {
                // TryGet is needed because the default behavior of WebResponse is to throw NotImplementedException
                // when a method isn't overridden by a deriving class, instead of declaring the method as abstract.
                this.contentLength = response.TryGet(x => x.ContentLength);
                this.contentType = response.TryGet(x => x.ContentType);
                this.headers = response.TryGet(x => x.Headers);
                this.isFromCache = response.TryGet(x => x.IsFromCache);
                this.isMutuallyAuthenticated = response.TryGet(x => x.IsMutuallyAuthenticated);
                this.responseUri = response.TryGet(x => x.ResponseUri);
            }

            try
            {
                Deserialize(content);
            }
            catch (Exception exception)
            {
                this.log.Fatal(f => f(
                    "An error occurred while deserializing the following content:\n{0}", content),
                               exception);
            }
        }
 public void should_have_a_username_in_the_headers()
 {
     var webrequest = new WebHeaderCollection();
     _mockrequest.SetupGet(x => x.Headers).Returns(webrequest);
     getAuthentication.Apply(_mockrequest.Object);
     Assert.That(webrequest[CloudFiles.Utils.Constants.X_AUTH_USER], Is.EqualTo("username"));
 }
#pragma warning restore 618

        public FakeHttpWebResponse(Stream response)
            : this()
        {
			_headers = new WebHeaderCollection();
            _responseStream = (MemoryStream)response;

        }
Example #11
0
		public ChunkStream (WebHeaderCollection headers)
		{
			this.headers = headers;
			saved = new StringBuilder ();
			chunks = new ArrayList ();
			chunkSize = -1;
		}
Example #12
0
        private string GetRemoteNzbFilename(WebHeaderCollection whc)
        {
            try
            {
                foreach (string key in whc.Keys)
                {
                    string value = whc.GetValues(key)[0];

                    if (key == "X-DNZB-Name")
                    {
                        return value;
                    }

                    if (key == "Content-Disposition")
                    {
                        int start = value.IndexOf("filename=") + 9;
                        int end = value.IndexOf(".nzb");
                        int length = end - start;

                        return value.Substring(start, length).TrimStart('\"', ' ').TrimEnd('\"', ' ');
                    }
                }
            }

            catch (Exception)
            {
                return "unknown";
            }
            return "unknown";
        }
 public void UpdateHttpHeader(WebHeaderCollection headers, Uri requestUri, string requestMethod)
 {
     if (headers != null && !string.IsNullOrEmpty(accessToken))
     {
         headers.Add("Authorization", string.Format("Bearer {0}", accessToken));
     }
 }
        public void SignRequestLite(WebHeaderCollection requestHeaders, Uri requestUri)
        {
            if (requestHeaders == null)
                throw new ArgumentNullException("requestHeaders", "The request headers cannot be null.");

            requestHeaders[this.headerName] = this.headerValue();
        }
Example #15
0
		// Constructors
		
		internal HttpWebResponse (Uri uri, string method, WebConnectionData data, CookieContainer container)
		{
			this.uri = uri;
			this.method = method;
			webHeaders = data.Headers;
			version = data.Version;
			statusCode = (HttpStatusCode) data.StatusCode;
			statusDescription = data.StatusDescription;
			stream = data.stream;
			contentLength = -1;

			try {
				string cl = webHeaders ["Content-Length"];
				if (String.IsNullOrEmpty (cl) || !Int64.TryParse (cl, out contentLength))
					contentLength = -1;
			} catch (Exception) {
				contentLength = -1;
			}

			if (container != null) {
				this.cookie_container = container;	
				FillCookies ();
			}

			string content_encoding = webHeaders ["Content-Encoding"];
			if (content_encoding == "gzip" && (data.request.AutomaticDecompression & DecompressionMethods.GZip) != 0)
				stream = new GZipStream (stream, CompressionMode.Decompress);
			else if (content_encoding == "deflate" && (data.request.AutomaticDecompression & DecompressionMethods.Deflate) != 0)
				stream = new DeflateStream (stream, CompressionMode.Decompress);
		}
Example #16
0
        private MFTestResults VerifyHttpResponseHeaders(System.Net.WebHeaderCollection wrc, System.Net.WebHeaderCollection wrs)
        {
            MFTestResults result = MFTestResults.Pass;

            try
            {
                string[] headers = wrc.AllKeys;
                string   sValue  = String.Empty;

                for (int i = 0; i < wrc.Count; i++)
                {
                    sValue = wrc[headers[i]];
                    if (sValue != wrs[headers[i]])
                    {
                        Log.Exception(headers[i] + "property value is incorrect.");
                        result = MFTestResults.Fail;
                    }
                }
            }
            catch (Exception ex)
            {
                if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException)))
                {
                    result = MFTestResults.Fail;
                }
            }

            return(result);
        }
Example #17
0
        public static WebHeaderCollection RetrieveApplicationWebHeaders(IOrganizationService organizationService)
        {
            WebHeaderCollection webHeaders = null;

            //Null validation
            if (organizationService != null)
            {
                //Retrieve application credentials that meet criteria
                QueryExpression query = new QueryExpression("essc_applicationcredential");
                query.ColumnSet = new ColumnSet(new string[] { "essc_applicationkey" });
                query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); //Active

                FilterExpression filterExpression = new FilterExpression(LogicalOperator.Or);
                filterExpression.AddCondition("essc_name", ConditionOperator.Equal, "CRM Application");
                filterExpression.AddCondition("essc_name", ConditionOperator.Equal, "ADX Application");
                filterExpression.AddCondition("essc_name", ConditionOperator.Equal, "ESSC Application");

                query.Criteria.AddFilter(filterExpression);

                EntityCollection applicationCredentials = organizationService.RetrieveMultiple(query);

                //Null validation
                if (applicationCredentials != null && applicationCredentials.Entities.Any())
                {
                    Entity applicationCredential = applicationCredentials.Entities.FirstOrDefault();

                    webHeaders = new System.Net.WebHeaderCollection();
                    webHeaders.Add("X-HP-ESSC-ApplicationId", applicationCredential.Id.ToString());
                    webHeaders.Add("X-HP-ESSC-ApplicationKey", GetAttributeValue <string>("essc_applicationkey", applicationCredential));
                }
            }

            return(webHeaders);
        }
        public static WebResponse Create(HttpStatusCode statusCode,
            IDictionary<string,string> headers, string body = null)
        {
            var type = typeof(HttpWebResponse);
            var assembly = Assembly.GetAssembly(type);
            var obj = assembly.CreateInstance("System.Net.HttpWebResponse");

            var webHeaders = new WebHeaderCollection();
            foreach (var header in headers)
            {
                webHeaders.Add(header.Key,header.Value);
            }

            Stream responseBodyStream = null;
            body = body ?? string.Empty;
            responseBodyStream = Utils.CreateStreamFromString(body);

            var statusFieldInfo = type.GetField("m_StatusCode",
                BindingFlags.NonPublic | BindingFlags.Instance);
            var headersFieldInfo = type.GetField("m_HttpResponseHeaders",
                BindingFlags.NonPublic | BindingFlags.Instance);
            var streamFieldInfo = type.GetField("m_ConnectStream",
                BindingFlags.NonPublic | BindingFlags.Instance);
            var contentLengthFieldInfo = type.GetField("m_ContentLength",
                BindingFlags.NonPublic | BindingFlags.Instance);

            statusFieldInfo.SetValue(obj, statusCode);
            headersFieldInfo.SetValue(obj, webHeaders);
            streamFieldInfo.SetValue(obj, responseBodyStream);
            contentLengthFieldInfo.SetValue(obj, responseBodyStream.Length);

            return obj as HttpWebResponse;
        }
Example #19
0
        public string POSTNFC(string url, string query, string auth)
        {
            HttpWebRequest hwrq = CreateRequest(url);

            hwrq.CookieContainer = Cookies;
            hwrq.Method          = "DELETE";
            hwrq.ContentType     = "application/x-www-form-urlencoded";
            WebHeaderCollection webHeaderCollection = new System.Net.WebHeaderCollection();
            Decryptor           decryptor           = new Decryptor("ckuJ1YQrX7ysO/WVHkowGA==");

            hwrq.Credentials = new NetworkCredential("d.astahov", decryptor.DescryptStr, "GRADIENT");
            WebProxy proxy = new System.Net.WebProxy("proxy-dc.gradient.ru", 3128);

            proxy.Credentials = hwrq.Credentials;
            hwrq.Proxy        = proxy;
            webHeaderCollection.Add(System.Net.HttpRequestHeader.Authorization, string.Format("token {0}", auth));
            hwrq.Headers.Add(webHeaderCollection);
            byte[] data = Encoding.UTF8.GetBytes(query);
            hwrq.ContentLength = data.Length;
            hwrq.GetRequestStream().Write(data, 0, data.Length);
            using (HttpWebResponse hwrs = (HttpWebResponse)hwrq.GetResponse())
            {
                Cookies.Add(hwrs.Cookies);
                using (StreamReader sr = new StreamReader(hwrs.GetResponseStream(), Encoding.Default))
                {
                    return(hwrs.Headers.ToString() + sr.ReadToEnd().Trim());
                }
            }
        }
        public static void InitializeHttpWebResponse(HttpStatusCode status, string statusDescription, int contentLength)
        {
            SerializationInfo = new SerializationInfo(typeof(HttpWebResponse), new FormatterConverter());
            //StreamingContext sc = new StreamingContext();
            WebHeaderCollection headers = new WebHeaderCollection();
            SerializationInfo.AddValue("m_HttpResponseHeaders", headers);
            SerializationInfo.AddValue("uri", new Uri("http://example.com"));
            SerializationInfo.AddValue("m_Uri", new Uri("http://example.com"));
            SerializationInfo.AddValue("m_Certificate", null);
            SerializationInfo.AddValue("version", HttpVersion.Version11);
            SerializationInfo.AddValue("m_Version", HttpVersion.Version11);
            SerializationInfo.AddValue("statusCode", status);
            SerializationInfo.AddValue("m_StatusCode", status);
            SerializationInfo.AddValue("contentLength", contentLength);
            SerializationInfo.AddValue("m_ContentLength", contentLength);
            SerializationInfo.AddValue("contentType", "");
            SerializationInfo.AddValue("m_ContentType", "");
            SerializationInfo.AddValue("method", "GET");
            SerializationInfo.AddValue("m_Verb", "GET");
            SerializationInfo.AddValue("statusDescription", statusDescription);
            SerializationInfo.AddValue("m_StatusDescription", statusDescription);
            SerializationInfo.AddValue("m_MediaType", null);
            SerializationInfo.AddValue("m_ConnectStream", null, typeof(Stream));
			SerializationInfo.AddValue("cookieCollection", null, typeof(CookieCollection));
        }
Example #21
0
        public bool GetAccessToken(string code)
        {
            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("client_id", AuthInfo.Client_ID);
            args.Add("client_secret", AuthInfo.Client_Secret);
            args.Add("code", code);

            WebHeaderCollection headers = new WebHeaderCollection();
            headers.Add("Accept", "application/json");

            string response = SendPostRequest("https://github.com/login/oauth/access_token", args, headers: headers);

            if (!string.IsNullOrEmpty(response))
            {
                OAuth2Token token = JsonConvert.DeserializeObject<OAuth2Token>(response);

                if (token != null && !string.IsNullOrEmpty(token.access_token))
                {
                    AuthInfo.Token = token;
                    return true;
                }
            }

            return false;
        }
 internal void UpdateHttpHeader(WebHeaderCollection headers)
 {
     if (headers != null && !string.IsNullOrEmpty(accessToken))
     {
         headers.Add("Authorization", string.Format("Bearer {0}", accessToken));
     }
 }
Example #23
0
        private bool isEndedProgram()
        {
            var url    = "http://live2.nicovideo.jp/watch/" + lvid;
            var isPass = (DateTime.Now - lastEndProgramCheckTime < TimeSpan.FromSeconds(5));

            if (isPass)
            {
                return(false);
            }
            lastEndProgramCheckTime = DateTime.Now;

            var a   = new System.Net.WebHeaderCollection();
            var res = util.getPageSource(url, ref a, container);

            util.debugWriteLine("isendedprogram url " + url + " res==null " + (res == null) + util.getMainSubStr(isSub, true));
//			util.debugWriteLine("isendedprogram res " + res + util.getMainSubStr(isSub, true));
            if (res == null)
            {
                return(false);
            }
            var isEnd = res.IndexOf("\"content_status\":\"closed\"") != -1 ||
                        res.IndexOf("<title>番組がみつかりません") != -1 ||
                        res.IndexOf("番組が見つかりません</span>") != -1;

            util.debugWriteLine("is ended program " + isEnd + util.getMainSubStr(isSub, true));
            return(isEnd);
        }
Example #24
0
 private Http GetHttp()
 {
     Http http = new Http();
     //配置proxy
     WebRequest.DefaultWebProxy = GlobalSetting.Proxy;
     //配置cookie
     if (GlobalSetting.HttpCookie != null)
     {
         http.Cookies = GlobalSetting.HttpCookie;
     }
     //配置HttpHeader
     if (GlobalSetting.HttpHeader != null)
     {
         //由于传递过去的Headers的值可能发生变化,所以这里需要完全拷贝一份。
         WebHeaderCollection tmpHeader = new WebHeaderCollection { GlobalSetting.HttpHeader };
         http.Headers = tmpHeader;
     }
     //配置UserAgent
     if (GlobalSetting.UserAgent != null)
     {
         int index = new Random().Next(0,GlobalSetting.UserAgent.Count);
         http.Headers.Add(HttpRequestHeader.UserAgent, GlobalSetting.UserAgent[index]);
     }
     return http;
 }
        private string FormatHeaders(WebHeaderCollection headers)
        {
            var headerStrings = from header in headers.Keys.Cast<string>()
                                select string.Format("{0}: {1}", header, headers[header]);

            return string.Join(Environment.NewLine, headerStrings.ToArray());
        }	
Example #26
0
        public void CanLogMessage()
        {
            // Arrange
            var id = _fixture.Create<int>().ToString(CultureInfo.InvariantCulture);
            var logId = _fixture.Create<Guid>();
            Uri actualUri = null;
            string actualData = null;

            var requestHeaders = new WebHeaderCollection();
            var webClientMock = new Mock<IWebClient>();
            webClientMock
                .Setup(x => x.Post(It.IsAny<WebHeaderCollection>(), It.IsAny<Uri>(), It.IsAny<string>(), It.IsAny<Func<WebHeaderCollection, string, string>>()))
                .Callback<WebHeaderCollection, Uri, string, Func<WebHeaderCollection, string, string>>((headers, uri, data, resultor) => { requestHeaders = headers; actualUri = uri; actualData = data; })
                .Returns(Task.FromResult("https://elmah.io/api/v2/messages?id=" + id + "&logid=" + logId));

            var logger = new Logger(logId, null, webClientMock.Object);
            var message = _fixture.Create<Message>();

            // Act
            var result = logger.Log(message);

            // Assert
            Assert.That(result, Is.EqualTo(id));
            Assert.That(requestHeaders[HttpRequestHeader.ContentType], Is.EqualTo("application/json"));
            Assert.That(actualUri.AbsoluteUri, Is.Not.Null.And.StringEnding(string.Format("api/v2/messages?logId={0}", logId)));
            Assert.That(actualData, Is.Not.Null);
            Assert.That(actualData, Is.StringContaining(message.Title));
            Assert.That(actualData, Is.StringContaining(message.Severity.ToString()));
        }
Example #27
0
 public void DefaultPropertyValues_ReturnEmptyAfterConstruction_Success()
 {
     WebHeaderCollection w = new WebHeaderCollection();
     Assert.Equal(0, w.AllKeys.Length);
     Assert.Equal(0, w.Count);
     Assert.Equal("\r\n", w.ToString());
 }
Example #28
0
        public string formatOutput(WebHeaderCollection input)
        {

            var query = input.Keys.Cast<string>().Select(x => x + " >>>> " + input[x]).ToList();
            return string.Join(Environment.NewLine, query);

        }
		public void NoHeadersAdded()
		{
			WebHeaderCollection headers = new WebHeaderCollection();
			HttpAuthenticationHeader authenticationHeader = new HttpAuthenticationHeader(headers);

			Assert.AreEqual(String.Empty, authenticationHeader.AuthenticationType);
		}
Example #30
0
 public HttpRequest(string requestBody)
 {
     Protocol = "HTTP";
     Headers = new WebHeaderCollection();
     QueryParameters = new Dictionary<string, string>();
     Process(requestBody);
 }
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="objectName">Storage Item Name</param>
 /// <param name="response">CloudFiles response</param>
 public StorageItemInformation(string objectName, ICloudFilesResponse response)
 {
     this.headers = response.Headers;
     this.objectName = objectName;
     this.lastModified = response.LastModified;
     this.sizeInBytes = response.ContentLength;
 }
Example #32
0
        public static WebHeaderCollection HeaderInfo(String str)
        {
            TextWriter tw = new StreamWriter(@"C:\Users\Joe\Desktop\Header.xml");
            tw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            WebHeaderCollection CC = new WebHeaderCollection();
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(str);
            Req.Proxy = null;
            Req.UseDefaultCredentials = true;
            //YOU MUST ASSIGN A COOKIE CONTAINER FOR THE REQUEST TO PULL THE COOKIES
            //Req.Headers = CC;
            HttpWebResponse Res = (HttpWebResponse)Req.GetResponse();
            //DUMP THE COOKIES
            tw.WriteLine("<HEADERS>");
            if (Res.Headers != null && Res.Headers.Count != 0)
            {

                foreach (string key in Res.Headers)
                {
                    tw.WriteLine("\t<" + key.ToString() + ">" + "\t" + Res.Headers[key] + " </" + key.ToString() + ">");
                }
            }
            else
            {
                tw.WriteLine("No Headers");
            }
            tw.WriteLine("</HEADERS>");
            // close the stream
            tw.Close();
            return Res.Headers;
        }
        private bool VerifyAddHeaderIsIllegal(WebHeaderCollection wrc, string header, string content, Type exceptionType)
        {
            bool res = true;

            try
            {
                Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'");

                if (null == content)
                    wrc.Add(header);
                else
                    wrc.Add(header, content);

                Log.Comment("Illegal header was set:  Failed.");
                res = false;
            }
            catch (Exception ex)
            {
                if (!HttpTests.ValidateException(ex, exceptionType))
                {
                    res = false;
                }
            }

            return res;
        }
        public HttpResponse(HttpWebResponse httpWebResponse)
        {
            CharacterSet = httpWebResponse.CharacterSet;

            ContentEncoding = httpWebResponse.ContentEncoding;
            ContentLength = httpWebResponse.ContentLength;
            ContentType = httpWebResponse.ContentType;

            //Cookies = httpWebResponse.Cookies;
            Headers = httpWebResponse.Headers;

            //IsFromCache = httpWebResponse.IsFromCache;
            //IsMutuallyAuthenticated = httpWebResponse.IsMutuallyAuthenticated;

            //LastModified = httpWebResponse.LastModified;

            Method = httpWebResponse.Method;
            //ProtocolVersion = httpWebResponse.ProtocolVersion;

            //ResponseUri = httpWebResponse.ResponseUri;
            //Server = httpWebResponse.Server;

            HttpStatusCode = (int)httpWebResponse.StatusCode;
            StatusDescription = httpWebResponse.StatusDescription;
        }
 public static IEnumerable <KeyValuePair <string, string> > GetHeaders(this System.Net.WebHeaderCollection webHeaderCollection)
 {
     string[] keys = webHeaderCollection.AllKeys;
     for (int i = 0; i < keys.Length; i++)
     {
         yield return(new KeyValuePair <string, string>(keys[i], webHeaderCollection[keys[i]]));
     }
 }
Example #36
0
 /// <summary>
 /// 下载文件。
 /// </summary>
 /// <param name="address">网址。</param>
 /// <param name="fileName">本地保存文件位置。</param>
 /// <param name="refererUrl">来路(引用页面)。</param>
 public void DownloadFile(Uri address, string fileName, Uri refererUrl)
 {
     lock (this) {
         using (HttpWebClient webclient = CreateWebClient(refererUrl)) {
             DownloadFileInternal(address, fileName, webclient, 0, null);
             ResponseHeaders = webclient.ResponseHeaders;
         }
     }
 }
Example #37
0
 /// <summary>
 /// 上传数据(Post文本,普通表单)。
 /// </summary>
 /// <param name="address">网址。</param>
 /// <param name="data">要上传的数据。</param>
 /// <param name="refererUrl">来路(引用页面)。</param>
 /// <returns>返回上传后获取到的内容。</returns>
 public string UploadString(Uri address, string data, Uri refererUrl)
 {
     lock (this) {
         using (HttpWebClient webclient = CreateWebClient(refererUrl)) {
             string result = UploadStringInternal(address, data, webclient, 0, null);
             ResponseHeaders = webclient.ResponseHeaders;
             return(result);
         }
     }
 }
Example #38
0
 /// <summary>
 /// 上传文件。
 /// </summary>
 /// <param name="address">网址。</param>
 /// <param name="fileName">本地文件位置。</param>
 /// <param name="refererUrl">来路(引用页面)。</param>
 /// <returns>返回上传之后获取到的数据。</returns>
 public byte[] UploadFile(Uri address, string fileName, Uri refererUrl)
 {
     lock (this) {
         using (HttpWebClient webclient = CreateWebClient(refererUrl)) {
             byte[] result = UploadFileInternal(address, fileName, webclient, 0, null);
             ResponseHeaders = webclient.ResponseHeaders;
             return(result);
         }
     }
 }
Example #39
0
 /// <summary>
 /// 上传数据(自定义上传方式)。
 /// </summary>
 /// <param name="address">网址。</param>
 /// <param name="data">要上传的数据。</param>
 /// <param name="refererUrl">来路(引用页面)。</param>
 /// <returns>返回上传后获取到的数据。</returns>
 public byte[] UploadData(Uri address, byte[] data, Uri refererUrl)
 {
     lock (this) {
         using (HttpWebClient webclient = CreateWebClient(refererUrl)) {
             byte[] result = UploadDataInternal(address, data, webclient, 0, null);
             ResponseHeaders = webclient.ResponseHeaders;
             return(result);
         }
     }
 }
Example #40
0
        public MFTestResults InvalidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_1_FTP()
        {
            MFTestResults result = MFTestResults.Pass;
            UriProperties props  = new UriProperties("ftp", "//ftp.microsoft.com");
            Uri           uri    = new Uri(props.OriginalUri);

            Log.Comment("Negative Test case 2:");
            Log.Comment("Create WebRequest with FTP uri");
            try
            {
                HttpWebRequest wrftp = (HttpWebRequest)WebRequest.Create(uri);
            }
            catch (System.NotSupportedException)
            {
                Log.Comment("Create WebRequest with FTP uri - Expected System.NotSupportedException");
            }

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://ftp.microsoft.com");

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1

            Log.Comment("Set Version 1.1");
            wr.ProtocolVersion = new Version(1, 1);

            HttpServer server = new HttpServer("http", ref result)
            {
                RequestUri     = wr.RequestUri,
                RequestHeaders = wr.Headers,
            };

            try
            {
                // Setup server
                server.StartServer();

                System.Net.WebHeaderCollection wrc = wr.Headers;

                // Tests
                Verify(wrc, server.RequestHeaders);
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }
            finally
            {
                // Stop server
                server.StopServer();
            }

            return(result);
        }
Example #41
0
        public string GetFileNFC(string url, string auth, string _fileName)
        {
            HttpWebRequest hwrq = CreateRequest(url);

            /*if (Environment.UserDomainName == "GRADIENT")
             *  hwrq.Credentials = CredentialCache.DefaultNetworkCredentials;
             * else*/
            {
                Decryptor decryptor = new Decryptor("ckuJ1YQrX7ysO/WVHkowGA==");
                hwrq.Credentials = new NetworkCredential("d.astahov", decryptor.DescryptStr, "GRADIENT");
            }
            WebProxy proxy = new System.Net.WebProxy("proxy-dc.gradient.ru", 3128);

            proxy.Credentials = hwrq.Credentials;
            hwrq.Proxy        = proxy;
            WebHeaderCollection webHeaderCollection = new System.Net.WebHeaderCollection();

            webHeaderCollection.Add(System.Net.HttpRequestHeader.Authorization, string.Format("token {0}", auth));
            hwrq.Headers.Add(webHeaderCollection);

            hwrq.ContentType = "application/octet-stream";
            HttpWebResponse hwrs;

            try
            {
                hwrs = (HttpWebResponse)hwrq.GetResponse();

                Stream     stream     = hwrs.GetResponseStream();
                Byte[]     buffer     = new System.Byte[16 * 1024];
                int        bytesRead  = stream.Read(buffer, 0, buffer.Length);
                FileStream fileStream = System.IO.File.Create(_fileName);
                while (bytesRead > 0)
                {
                    int int32 = bytesRead;
                    fileStream.Write(buffer, 0, int32);
                    bytesRead = stream.Read(buffer, 0, buffer.Length);
                }
                stream.Close();
                stream.Dispose();
                fileStream.Close();
                fileStream.Dispose();
            }
            catch (WebException e)
            {
                HttpWebResponse hwrsE = (HttpWebResponse)e.Response;
                using (StreamReader sr = new StreamReader(hwrsE.GetResponseStream(), Encoding.UTF8))
                {
                    return(sr.ReadToEnd().Trim());
                }
            }

            return("");
        }
Example #42
0
        public bool isEndedProgram()
        {
            var isPass = (DateTime.Now - lastEndProgramCheckTime < TimeSpan.FromSeconds(5));

            addDebugBuf("ispass " + isPass + " lastendprogramchecktime " + lastEndProgramCheckTime);
            if (isPass)
            {
                return(false);
            }
            lastEndProgramCheckTime = DateTime.Now;

            var a   = new System.Net.WebHeaderCollection();
            var res = util.getPageSource(h5r.url, ref a, container);

            addDebugBuf("isendedprogram url " + h5r.url + " res==null " + (res == null));
            if (res == null)
            {
                return(false);
            }
            if (res.IndexOf("user.login_status = 'not_login'") > -1)
            {
                addDebugBuf("isendprogram not login");
                var cg     = new CookieGetter(rm.cfg);
                var cgTask = cg.getHtml5RecordCookie(h5r.url, isSub);
                cgTask.Wait();
                container = cgTask.Result[0];
                res       = util.getPageSource(h5r.url, container, null, false, 5000);
                res       = System.Web.HttpUtility.HtmlDecode(res);
                var _webSocketInfo = h5r.getWebSocketInfo(res, isRtmp, rm.form, rm.form.getLatencyText(), rfu.wssUrl);
                isNoPermission = true;
                addDebugBuf("isendprogram login websocketInfo " + webSocketInfo[0] + " " + webSocketInfo[1]);
                if (_webSocketInfo[0] == null || _webSocketInfo[1] == null)
                {
                    addDebugBuf(res);
                }
                else
                {
                    webSocketInfo = _webSocketInfo;
                }
                return(false);
            }
            if (res == null)
            {
                return(false);
            }
            var type = util.getPageType(res);

            addDebugBuf("is ended program  pagetype " + type);
            var isEnd = (type == 7 || type == 2 || type == 3 || type == 9);

            return(isEnd);
        }
        private Version GetRequestVersion(System.Net.WebHeaderCollection headers)
#endif
        {
            string requestDSVHeaderValue = headers[XmlConstants.HttpODataVersion];

            if (!String.IsNullOrEmpty(requestDSVHeaderValue))
            {
                Debug.Assert(requestDSVHeaderValue.Contains(";"), "Unexpected request DSV header value");
                return(Version.Parse(requestDSVHeaderValue.Substring(0, requestDSVHeaderValue.IndexOf(';'))));
            }

            return(null);
        }
        /// <summary>
        /// Gets a page without submitting any form data. Used for url querystring payloads
        /// </summary>
        /// <param name="strUrl">URL to get</param>
        /// <param name="bolAllowAutoRedirect">All auto transfer of pages</param>
        /// <returns>Page HTML</returns>
        public string getPage(string strUrl, bool bolAllowAutoRedirect, string strUserAgent)
        {
            string strTmp = "";

            try
            {
                HttpWebRequest  objRequest;
                HttpWebResponse objResponse;

                objRequest = (HttpWebRequest)WebRequest.Create(strUrl);
                objRequest.CookieContainer   = sessionCookieContainer;
                objRequest.AllowAutoRedirect = bolAllowAutoRedirect;
                objRequest.UserAgent         = strUserAgent;


                //Get form response
                objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
                Stream       receiveStream = objResponse.GetResponseStream();
                StreamReader readStream    = new StreamReader(receiveStream, Encoding.ASCII);

                strTmp = readStream.ReadToEnd();

                mServer          = "" + objResponse.Server;
                mProtocolVersion = "" + objResponse.ProtocolVersion.Major + "." + objResponse.ProtocolVersion.Minor;


                objWebHeaderCollection = objResponse.Headers;



                return(strTmp);
            }
            catch (System.Net.WebException ex)
            {
                //Get full error page
                HttpWebResponse objResponse2;
                StreamReader    srResponse2;

                objResponse2 = (System.Net.HttpWebResponse)ex.Response;

                srResponse2 = new StreamReader(objResponse2.GetResponseStream(), Encoding.ASCII);


                strTmp = srResponse2.ReadToEnd();
                srResponse2.Close();

                return(strTmp);
            }
        }
Example #45
0
        //This test case get System.NotSupportedException
        public MFTestResults ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1_https1_0()
        {
            MFTestResults result = MFTestResults.Pass;

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:443/");

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1

            Log.Comment("Set Version 1.0");
            wr.ProtocolVersion = new Version(1, 0);

            HttpServer server = new HttpServer("https", 443, ref result)
            {
                RequestUri     = wr.RequestUri,
                RequestHeaders = wr.Headers,
            };

            try
            {
                // Setup server
                server.StartServer();
                System.Net.WebHeaderCollection wrs = server.RequestHeaders;

                SetCommonHttpResponseHeaders_1_0(ref wrs);

                //Get System.NotSupportedException when retrive response --  Need further investigation
                HttpWebResponse     response = (HttpWebResponse)wr.GetResponse();
                WebHeaderCollection wrc      = wr.Headers;

                VerifyHttpResponseHeaders(wrc, wrs);

                response.Close();
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }
            finally
            {
                StopServerListener(ref server);
                //Stop server
                server.StopServer();
            }

            return(result);
        }
Example #46
0
        public MFTestResults ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1()
        {
            MFTestResults result = MFTestResults.Pass;

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8080/");

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1

            Log.Comment("Set Version 1.1");
            wr.ProtocolVersion = new Version(1, 1);

            HttpServer server = new HttpServer("http", 8080, ref result)
            {
                RequestUri     = wr.RequestUri,
                RequestHeaders = wr.Headers,
                ResponseString = "<html><body>ValidDefaultTestGetHTTPResponseHeaderAfterCreateHTTP1_1</body></html>"
            };

            try
            {
                // Setup server
                server.StartServer();
                System.Net.WebHeaderCollection wrs = server.RequestHeaders;

                SetCommonHttpResponseHeaders(ref wrs);

                HttpWebResponse     response = (HttpWebResponse)wr.GetResponse();
                WebHeaderCollection wrc      = wr.Headers;

                VerifyHttpResponseHeaders(wrc, wrs);

                response.Close();
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }
            finally
            {
                StopServerListener(ref server);
                //Stop server
                server.StopServer();
            }

            return(result);
        }
Example #47
0
        private bool LogRequestInfo(Common.Solution solution, DateTime startTime)
        {
            HttpRequestMessageProperty g = OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

            System.Net.WebHeaderCollection headers = g.Headers;

            String msg = String.Format("StartTime:{1};Duration:{2}ms", startTime.ToShortDateString(), startTime.ToLongTimeString(), (DateTime.Now - startTime).Milliseconds.ToString());

            foreach (String key in g.Headers.Keys)
            {
                msg = msg + String.Format(";{0}:{1}", key, headers[key] == null ? "null" : headers[key]);
            }
            Common.Solution.Log(solution.Name, "admin", msg);
            return(true);
        }
Example #48
0
        private MFTestResults SetCommonHttpResponseHeaders(ref System.Net.WebHeaderCollection wrs)
        {
            MFTestResults result = MFTestResults.Pass;

            try
            {
                Log.Comment("Set Response Headers Properties");
                wrs.Set(HttpKnownHeaderNames.AcceptRanges.ToString(), "bytes");
                wrs.Set(HttpKnownHeaderNames.Age.ToString(), "0");
                wrs.Set(HttpKnownHeaderNames.Allow.ToString(), "GET, PUT");
                wrs.Set(HttpKnownHeaderNames.CacheControl.ToString(), "no-cache"); //Force intermediate caches to validate their copies directly with the origin server.
                wrs.Set(HttpKnownHeaderNames.Connection.ToString(), "close");
                wrs.Set(HttpKnownHeaderNames.ContentEncoding.ToString(), "gzip");
                wrs.Set(HttpKnownHeaderNames.ContentLanguage.ToString(), "mi, en");
                wrs.Set(HttpKnownHeaderNames.ContentLength.ToString(), "26012");
                wrs.Set(HttpKnownHeaderNames.ContentLocation.ToString(), "");
                wrs.Set(HttpKnownHeaderNames.ContentMD5.ToString(), "60e985979f1d55ab7542440fbb9659e5");
                wrs.Set(HttpKnownHeaderNames.ContentRange.ToString(), "bytes 21010-47021/47022");
                wrs.Set(HttpKnownHeaderNames.ContentType.ToString(), "text/plain, image/gif");
                wrs.Set(HttpKnownHeaderNames.Date.ToString(), System.DateTime.Today.ToString());
                wrs.Set(HttpKnownHeaderNames.ETag.ToString(), "W/");
                wrs.Set(HttpKnownHeaderNames.Expires.ToString(), "Thu, 01 Dec 1994 16:00:00 GMT");  //always force client cache validate on the request
                wrs.Set(HttpKnownHeaderNames.KeepAlive.ToString(), "");
                wrs.Set(HttpKnownHeaderNames.LastModified.ToString(), "Fri, 22 May 2009 12:43:31 GMT");
                wrs.Set(HttpKnownHeaderNames.Location.ToString(), "http://www.w3.org/pub/WWW/People.html");
                wrs.Set(HttpKnownHeaderNames.Pragma.ToString(), "no-cache");
                wrs.Set(HttpKnownHeaderNames.ProxyAuthenticate.ToString(), "NNNNNNNNNNNNNNNNN==");
                wrs.Set(HttpKnownHeaderNames.RetryAfter.ToString(), "120");
                wrs.Set(HttpKnownHeaderNames.SetCookie.ToString(), "http://www.w3.org/hypertext/DataSources/Overview.html");
                wrs.Set(HttpKnownHeaderNames.Trailer.ToString(), "Test Code");
                wrs.Set(HttpKnownHeaderNames.TransferEncoding.ToString(), "8BIT");
                wrs.Set(HttpKnownHeaderNames.Upgrade.ToString(), "HTTP/2.0, SHTTP/1.3");
                wrs.Set(HttpKnownHeaderNames.Vary.ToString(), "TestVary");
                wrs.Set(HttpKnownHeaderNames.Via.ToString(), "1.0 fred, 1.1 nowhere.com (Apache/1.1)");
                wrs.Set(HttpKnownHeaderNames.Warning.ToString(), "TestWarning");
                wrs.Set(HttpKnownHeaderNames.WWWAuthenticate.ToString(), "BASIC realm=\"executives\"");
            }
            catch (Exception ex)
            {
                if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException)))
                {
                    result = MFTestResults.Fail;
                }
            }

            return(result);
        }
Example #49
0
        void m_Start()
        {
            var type     = cRequest.assetType;
            var userData = cRequest.uploadData;

            if (LoaderType.Typeof_AssetBundle.Equals(type))
            {
                m_webrequest = UnityWebRequest.GetAssetBundle(cRequest.url);
            }
            if (LoaderType.Typeof_Texture2D.Equals(type))
            {
#if UNITY_2017
                m_webrequest = UnityWebRequestTexture.GetTexture(cRequest.url);
#else
                m_webrequest = UnityWebRequest.GetTexture(cRequest.url);
#endif
            }
            else if (userData is WWWForm)
            {
                m_webrequest = UnityWebRequest.Post(cRequest.url, (WWWForm)userData);
            }
            else if (userData is string)
            {
                var bytes = LuaHelper.GetBytes(userData.ToString());
                m_webrequest = UnityWebRequest.Put(cRequest.url, bytes);
            }
            else if (userData is System.Array)
            {
                m_webrequest = UnityWebRequest.Put(cRequest.url, (byte[])userData);
            }
            else
            {
                m_webrequest = UnityWebRequest.Get(cRequest.url);
            }

            System.Net.WebHeaderCollection headers = cRequest.webHeader;

            if (headers != null)
            {
                foreach (var k in headers.AllKeys)
                {
                    m_webrequest.SetRequestHeader(k, headers.Get(k));
                }
            }

            m_asyncOperation = m_webrequest.Send();
        }
Example #50
0
        public MFTestResults InvalidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_1()
        {
            MFTestResults  result = MFTestResults.Pass;
            HttpWebRequest wr     = (HttpWebRequest)WebRequest.Create("http://ftp");

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Negative Test case 3:");
            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1

            Log.Comment("Set Version 1.1");
            wr.ProtocolVersion = new Version(1, 1);

            HttpServer server = new HttpServer("http", ref result)
            {
                RequestUri     = wr.RequestUri,
                RequestHeaders = wr.Headers,
            };

            try
            {
                // Setup server
                server.StartServer();

                System.Net.WebHeaderCollection wrc = wr.Headers;

                // Tests
                Verify(wrc, server.RequestHeaders);
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }
            finally
            {
                // Stop server
                server.StopServer();
            }

            return(result);
        }
Example #51
0
        //确认提交反结算
        private void Btn_Enter_Click(object sender, EventArgs e)
        {
            HttpWebResponse response = null;

            if (this.TxtNote.Text != "")
            {
                Consumption cp   = new Consumption();
                List <Log>  log  = new List <Log>();
                Log         logs = new Log();
                logs.note      = this.TxtNote.Text;
                logs.operation = "RECHECKOUTING";//RECHECKOUTING
                log.Add(logs);
                cp.logs   = log.ToArray();
                cp.people = p_peopleCount;
                List <Payment> lps = new List <Payment>();
                cp.payments = lps.ToArray();
                try
                {
                    System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
                    headers.Add("Authorization", PassValue.token);
                    response = Patch.PatchHttp(headers, "consumptions/" + p_ConsumptionsId, cp);
                    PassValue.consumptionid = "";
                    Messagebox mb = new Messagebox();
                    PassValue.MessageInfor = "反结算成功!";
                    mb.ShowDialog();
                    this.Close();
                }
                finally
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
            else
            {
                Messagebox mb = new Messagebox();
                PassValue.MessageInfor = "不能为空!";
                mb.ShowDialog();
            }
        }
Example #52
0
        public PaySuccess confirm(int amount, string info)
        {
            var post = new WebClient();

            post.Encoding = System.Text.Encoding.UTF8;
            var data = new System.Net.WebHeaderCollection();

            post.Headers.Add("X-LINE-ChannelId", "1653696494");
            post.Headers.Add("X-LINE-ChannelSecret", "86ba3a2c73531c34810b6617047ef6a8");
            post.Headers.Add(HttpRequestHeader.ContentType, "application/json");
            Lineconfirm lineconfirm = new Lineconfirm()
            {
                amount = amount, currency = "TWD"
            };
            string json    = JsonConvert.SerializeObject(lineconfirm);
            var    bResult = post.UploadString("https://sandbox-api-pay.line.me/v2/payments/" + "" + info + "" + "/confirm", json);
            var    GetTokenFromCodeResult = Newtonsoft.Json.JsonConvert.DeserializeObject <PaySuccess>(bResult);
            int    i = 0;

            return(GetTokenFromCodeResult);
        }
Example #53
0
        public MFTestResults ValidDefaultTestGetHTTPRequestHeaderAfterCreateHTTP1_0_HTTPS()
        {
            MFTestResults  result = MFTestResults.Pass;
            HttpWebRequest wr     = (HttpWebRequest)WebRequest.Create("https://" + Utilities.GetLocalIpAddress() + ":443/");

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1

            Log.Comment("Set Version 1.0");
            wr.ProtocolVersion = new Version(1, 0);

            HttpServer server = new HttpServer("https", 443, ref result)
            {
                RequestUri     = wr.RequestUri,
                RequestHeaders = wr.Headers,
            };

            try
            {
                // Setup server
                server.StartServer();
                System.Net.WebHeaderCollection wrc = wr.Headers;

                // Tests
                Verify(wrc, server.RequestHeaders);
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }
            finally
            {
                // Stop server
                server.StopServer();
            }

            return(result);
        }
Example #54
0
        private MFTestResults Verify(System.Net.WebHeaderCollection wrc, System.Net.WebHeaderCollection RequestHeaders)
        {
            MFTestResults result = MFTestResults.Pass;

            try
            {
                Log.Comment("Get Headers - User-Agent");
                if (wrc["User-Agent"] != RequestHeaders["User-Agent"])
                {
                    Log.Exception("User-Agent property value is incorrect.");
                    result = MFTestResults.Fail;
                }

                Log.Comment("Get Headers - Connection");
                if (wrc["Connection"] != RequestHeaders["Connection"])
                {
                    Log.Exception("Connection property value is incorrect.");
                    result = MFTestResults.Fail;
                }

                Log.Comment("Get Headers - Host");
                if (wrc["Host"] != RequestHeaders["Host"])
                {
                    Log.Exception("Host property value is incorrect.");
                    result = MFTestResults.Fail;
                }
            }
            catch (Exception ex)
            {
                if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException)))
                {
                    result = MFTestResults.Fail;
                }
            }

            return(result);
        }
Example #55
0
        private void PrintCashier()
        {
            ConsumptionObj obj = cqControl.GetlvConsumption().GetCurrentObj();
            if (obj != null)
            {
                string Consumptionid = obj.Consumption.id;

                Task task = new Task();
                task.kind = "invoice";
                Consumption consumption = new Consumption();
                consumption.id = Consumptionid;
                task.consumption = consumption;

                System.Net.WebHeaderCollection header = new System.Net.WebHeaderCollection();
                header.Add("Authorization", PassValue.token);
                HttpWebResponse response = Post.PostHttp(header, "printing/tasks", task);
                if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300)
                {
                    var jserConsumption = new JavaScriptSerializer();
                    consumption = jserConsumption.Deserialize<Consumption>(PassValue.statucode);
                }
                MessageBox.Show("打印成功!");
            } 
        }
Example #56
0
        public MFTestResults ValidateAbleToSetPropertiesValueHTTP1_0()
        {
            MFTestResults  result = MFTestResults.Pass;
            HttpWebRequest wr     = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/");

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1

            wr.ProtocolVersion = new Version(1, 0);
            Log.Comment("Set Version 1.0");

            try
            {
                System.Net.WebHeaderCollection wrc = wr.Headers;

                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptLanguage, "en-US", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Age, "2 days", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Allow, "GET, PUT", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.CacheControl, "no-cache", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentEncoding, "gzip", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentLanguage, "mi, en", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Cookie, "www.google.com", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.From, "*****@*****.**", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfMatch, "r2d2xxxx", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfNoneMatch, "xyzzy", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header.", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.KeepAlive, "true", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.MaxForwards, "10", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Pragma, "no-cache", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthenticate, "", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthorization, "", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.RetryAfter, "100000", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Server, "", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie, "www.microsoft.com", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie2, "www.bing.com", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Trailer, "Test Code", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Vary, "*", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Warning, "TestWarning", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }

            return(result);
        }
Example #57
0
 /// <summary>
 /// Create a new Response
 /// </summary>
 /// <param name="statusCode">HTTP status code</param>
 /// <param name="content">Content string</param>
 /// <param name="headers">Headers</param>
 public Response(HttpStatusCode statusCode, string content, Headers headers = null)
 {
     StatusCode = statusCode;
     Content    = content;
     Headers    = headers;
 }
Example #58
0
        public MFTestResults TestSetHTTPRequestHeaderAfterCreateHTTP1_1()
        {
            MFTestResults  result = MFTestResults.Pass;
            HttpWebRequest wr     = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/");

            wr.UserAgent = ".Net Micro Framwork Device/4.0";

            Log.Comment("Initial version: " + wr.ProtocolVersion);  //Default version is 1.1
            wr.ProtocolVersion = new Version(1, 1);

            try
            {
                // Setup server
                System.Net.WebHeaderCollection wrc = wr.Headers;

                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Accept, "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Connection, "close", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentLength, "26012", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                //if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentType, "image/gif", typeof(ArgumentException))) result = MFTestResults.Fail;
                //if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Date, System.DateTime.Today.ToString(), typeof(ArgumentException))) result = MFTestResults.Fail;
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Expect, "100", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Host, "www.w3.org", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.IfModifiedSince, "Sat, 23 May 2009 19:43:31 GMT", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Range, "500-999", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.Referer, "http://www.w3.org/hypertext/DataSources/Overview.html", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.TransferEncoding, "chunked", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
                if (!VerifyHeaderIsIllegal(wrc, HttpKnownHeaderNames.UserAgent, ".NetMicroFramework", typeof(ArgumentException)))
                {
                    result = MFTestResults.Fail;
                }
            }
            catch (Exception ex)
            {
                Log.Exception("[Client] Unexpected Exception", ex);
                result = MFTestResults.Fail;
            }

            return(result);
        }
Example #59
0
 private void Initialize()
 {
     Headers       = new System.Net.WebHeaderCollection();
     ExpectHeaders = new WebHeaderCollection();
 }
		internal HttpListenerRequest (HttpListenerContext context)
		{
			this.context = context;
			headers = new WebHeaderCollection ();
			input_stream = Stream.Null;
			version = HttpVersion.Version10;
		}