Esempio n. 1
0
        private void CheckForErrors(CodeScales.Http.Methods.HttpResponse response)
        {
            var status = EntityUtils.ToString(response.Entity);
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(status));

            using (var reader = XmlReader.Create(stream))
            {
                while (reader.Read())
                {
                    if (reader.IsStartElement())
                    {
                        switch (reader.Name)
                        {
                        case "result":
                            break;

                        case "message":     // success
                            return;

                        case "error":     // failure
                            throw new ProtocolViolationException(status);

                        default:
                            throw new ArgumentException("Unknown element: " + reader.Name);
                        }
                    }
                }
            }
        }
Esempio n. 2
0
        public static void SendWelcomeMail(string userName, string email)
        {
            HttpClient      client          = new HttpClient();
            HttpPost        postMethod      = new HttpPost(new Uri("http://sendcloud.sohu.com/webapi/mail.send_template.json"));
            MultipartEntity multipartEntity = new MultipartEntity();

            postMethod.Entity = multipartEntity;
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "template_invoke_name", "superjokes_register"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "substitution_vars", "{\"to\": [\"" + email + "\"], \"sub\" : { \"%username%\" : [\"" + userName + "\"]}}"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_user", "superjokes_cn"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_key", AppConfig.SendCloudKey));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "from", "*****@*****.**"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "fromname", "超级冷笑话"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "subject", "超级冷笑话注册邮件"));
            CodeScales.Http.Methods.HttpResponse response = client.Execute(postMethod);

            var repCode   = response.ResponseCode;
            var repResult = EntityUtils.ToString(response.Entity);
            //LogHelper.Info("reg:" + email + repResult + AppConfig.SendCloudKey);

            //Console.WriteLine("Response Code: " + response.ResponseCode);
            //Console.WriteLine("Response Content: " + EntityUtils.ToString(response.Entity));

            //Response.Write("Response Code: " + response.ResponseCode);
            //Response.Write("<br/>");
            //Response.Write("Response Content: " + EntityUtils.ToString(response.Entity));
        }
        internal void ReadCookiesFromResponse(HttpResponse response)
        {
            lock (this)
            {
                Uri responseUri = response.RequestUri;
                HttpCookieCollection cookieColl = null;
                if (this.m_cookieStore.ContainsKey(responseUri.Host))
                {
                    cookieColl = this.m_cookieStore[responseUri.Host];
                }
                else
                {
                    cookieColl = new HttpCookieCollection();
                    this.m_cookieStore.Add(responseUri.Host, cookieColl);
                }

                string [] cookieHeaders = response.Headers.GetValues("Set-Cookie");
                if (cookieHeaders != null)
                {

                    foreach (string header in cookieHeaders)
                    {
                        HTTPProtocol.AddHttpCookie(header, cookieColl);
                    }
                }
            }
        }
Esempio n. 4
0
		public void CheckKeepAlive(HttpResponse response)
		{
			var headers = response.Headers;

			if (!((headers[HTTP.CONN_DIRECTIVE] != null && headers[HTTP.CONN_DIRECTIVE].ToLower() == HTTP.CONN_KEEP_ALIVE) ||
				(headers[HTTP.PROXY_CONN_DIRECTIVE] != null && headers[HTTP.PROXY_CONN_DIRECTIVE].ToLower() == HTTP.CONN_KEEP_ALIVE)))
			{
				Close();
			}
		}
Esempio n. 5
0
        public static void VerifyNotice(string userName, string email, string jokeTitle, string jokeurl)
        {
            HttpClient      client          = new HttpClient();
            HttpPost        postMethod      = new HttpPost(new Uri("http://sendcloud.sohu.com/webapi/mail.send_template.json"));
            MultipartEntity multipartEntity = new MultipartEntity();

            postMethod.Entity = multipartEntity;
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "template_invoke_name", "superjokes_verifynotice"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "substitution_vars", "{\"to\": [\"" + email + "\"], \"sub\" : { \"%username%\" : [\"" + userName + "\"],\"%joketitle%\":[\"" + jokeTitle + "\"],\"%jokeurl%\":[\"" + jokeurl + "\"]}}"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_user", "superjokes_cn"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "api_key", AppConfig.SendCloudKey));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "from", "*****@*****.**"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "fromname", "超级冷笑话"));
            multipartEntity.AddBody(new StringBody(Encoding.UTF8, "subject", "超级冷笑话审核通知"));
            CodeScales.Http.Methods.HttpResponse response = client.Execute(postMethod);

            var repCode   = response.ResponseCode;
            var repResult = EntityUtils.ToString(response.Entity);
            //LogHelper.Info("verify:" + email + repResult + AppConfig.SendCloudKey);
        }
Esempio n. 6
0
		public override HttpResponse ReceiveResponseHeaders()
		{
			if (!IsConnected())
			{
				throw new HttpNetworkException("Tls client is closed or not ready (ReceiveResponseHeaders)");
			}

			WaitForDataToArrive(RequestTimeout);

			var httpResponse = new HttpResponse();
			httpResponse.RequestUri = Uri;
			var header = "";
			var headers = new WebHeaderCollection();

			var bytes = new byte[1];
			do
			{
				bytes[0] = _tlsClient.ReadByte();
				header += Encoding.ASCII.GetString(bytes, 0, 1);
				if (bytes[0] == '\n' && header.EndsWith("\r\n\r\n"))
					break;
			} while (bytes[0] > 0);

			MatchCollection matches = new Regex("[^\r\n]+").Matches(header.TrimEnd('\r', '\n'));
			for (int n = 1; n < matches.Count; n++)
			{
				string[] strItem = matches[n].Value.Split(new char[] {':'}, 2);
				if (strItem.Length > 1)
				{
					if (!strItem[0].Trim().ToLower().Equals("set-cookie"))
					{
						headers.Add(strItem[0].Trim(), strItem[1].Trim());
					}
					else
					{
						headers.Add(strItem[0].Trim(), strItem[1].Trim());
						// HTTPProtocol.AddHttpCookie(strItem[1].Trim(), cookieCollection);
					}
				}
			}

			httpResponse.Headers = headers;

			// set the response code
			if (matches.Count > 0)
			{
				try
				{
					string firstLine = matches[0].Value;
					int index1 = firstLine.IndexOf(" ");
					int index2 = firstLine.IndexOf(" ", index1 + 1);
					httpResponse.ResponseCode = Int32.Parse(firstLine.Substring(index1 + 1, index2 - index1 - 1));
				}
				catch (Exception ex)
				{
					throw new HttpNetworkException("Response Code is missing from the response");
				}
			}

			return httpResponse;
		}
Esempio n. 7
0
		public override void ReceiveResponseEntity(HttpResponse response)
		{
			if (!this.IsConnected())
			{
				throw new HttpNetworkException("Tls client is closed or not ready (ReceiveResponseEntity)");
			}

			string chunkedHeader = EntityUtils.GetTransferEncoding(response.Headers);
			if (chunkedHeader != null
				&& chunkedHeader.ToLower().Equals(HTTP.CHUNK_CODING))
			{
				List<byte> byteBuffer = new List<byte>();
				BasicHttpEntity httpEntity = new BasicHttpEntity();
				httpEntity.ContentLength = 0;
				httpEntity.ContentType = EntityUtils.GetContentType(response.Headers);
				response.Entity = httpEntity;

				int chunkSize = EntityUtils.ConvertHexToInt(ReceiveLine());
				while (chunkSize > 0)
				{
					// for each chunk...
					byteBuffer.AddRange(ReceiveBytes(chunkSize));
					httpEntity.ContentLength += chunkSize;
					string test = ReceiveLine();
					chunkSize = EntityUtils.ConvertHexToInt(ReceiveLine());
				}

				httpEntity.Content = byteBuffer.ToArray();
			}
			else
			{
				// TODO: support "Transfer-Encoding: chunked"
				int length = EntityUtils.GetContentLength(response.Headers);
				if (length > 0)
				{
					BasicHttpEntity httpEntity = new BasicHttpEntity();
					httpEntity.ContentLength = length;
					httpEntity.Content = ReceiveBytes(length).ToArray();
					httpEntity.ContentType = EntityUtils.GetContentType(response.Headers);
					response.Entity = httpEntity;
				}
			}

			return;
		}
        public void CheckKeepAlive(HttpResponse response)
        {
            WebHeaderCollection headers = response.Headers;

            if ((headers[HTTP.CONN_DIRECTIVE] != null && headers[HTTP.CONN_DIRECTIVE].ToLower() == HTTP.CONN_KEEP_ALIVE) ||
                (headers[HTTP.PROXY_CONN_DIRECTIVE] != null && headers[HTTP.PROXY_CONN_DIRECTIVE].ToLower() == HTTP.CONN_KEEP_ALIVE))
            {
                return;
            }
            else
            {
                this.Close();
            }
        }
        public HttpResponse ReceiveResponseHeaders()
        {
            if (!this.IsConnected())
            {
                throw new HttpNetworkException("Socket is closed or not ready");
            }

            WaitForDataToArriveAtSocket(this.m_timeout);

            HttpResponse httpResponse = new HttpResponse();
            httpResponse.RequestUri = this.Uri;
            string Header = "";
            WebHeaderCollection Headers = new WebHeaderCollection();

            byte[] bytes = new byte[10];
            while (this.m_socket.Receive(bytes, 0, 1, SocketFlags.None) > 0)
            {
                Header += Encoding.ASCII.GetString(bytes, 0, 1);
                if (bytes[0] == '\n' && Header.EndsWith("\r\n\r\n"))
                    break;
            }
            MatchCollection matches = new Regex("[^\r\n]+").Matches(Header.TrimEnd('\r', '\n'));
            for (int n = 1; n < matches.Count; n++)
            {
                string[] strItem = matches[n].Value.Split(new char[] { ':' }, 2);
                if (strItem.Length > 1)
                {
                    if (!strItem[0].Trim().ToLower().Equals("set-cookie"))
                    {
                        Headers.Add(strItem[0].Trim(), strItem[1].Trim());
                    }
                    else
                    {
                        Headers.Add(strItem[0].Trim(), strItem[1].Trim());
                        // HTTPProtocol.AddHttpCookie(strItem[1].Trim(), cookieCollection);
                    }
                }
            }

            httpResponse.Headers = Headers;

            // set the response code
            if (matches.Count > 0)
            {
                try
                {
                    string firstLine = matches[0].Value;
                    int index1 = firstLine.IndexOf(" ");
                    int index2 = firstLine.IndexOf(" ", index1 + 1);
                    httpResponse.ResponseCode = Int32.Parse(firstLine.Substring(index1 + 1, index2 - index1 - 1));
                }
                catch (Exception ex)
                {
                    throw new HttpNetworkException("Response Code is missing from the response");
                }
            }

            return httpResponse;
        }
Esempio n. 10
0
		public abstract void ReceiveResponseEntity(HttpResponse response);