Inheritance: WebRequest, ISerializable
 internal NonEntityOperationResult(object source, HttpWebRequest request, AsyncCallback callback, object state)
 {
   this.source = source;
   this.request = request;
   this.userCallback = callback;
   this.userState = state;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="WebRequestEventArgs"/> class
        /// with the specified web request.
        /// </summary>
        /// <param name="request">The HTTP web request.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="request"/> is <see langword="null"/>.</exception>
        public WebRequestEventArgs(HttpWebRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            _request = request;
        }
 private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
 {
     using (Stream stream = webRequest.GetRequestStream())
     {
         soapEnvelopeXml.Save(stream);
     }
 }
        /// <summary>
        /// Constructor with proxy credentials provided
        /// </summary>
        /// <param name="request">The request being sent to the server</param>
        /// <param name="proxyCredentials">Proxy credentials</param>
        /// <exception cref="System.ArgumentNullException">Thrown when any of the reference arguments are null</exception>
        public CloudFilesRequest(HttpWebRequest request, ProxyCredentials proxyCredentials)
        {
            if (request == null) throw new ArgumentNullException();

            _httpWebRequest = request;
            _proxyCredentials = proxyCredentials;
        }
Beispiel #5
2
		public static void CopyHeaders(HttpWebRequest src, HttpWebRequest dest)
		{
			foreach (string header in src.Headers)
			{
				var values = src.Headers.GetValues(header);
				if (values == null)
					continue;
				if (WebHeaderCollection.IsRestricted(header))
				{
					switch (header)
					{
						case "Accept":
							dest.Accept = src.Accept;
							break;
						case "Connection":
							// explicitly ignoring this
							break;
						case "Content-Length":
							break;
						case "Content-Type":
							dest.ContentType = src.ContentType;
							break;
						case "Date":
							break;
						case "Expect":
							// explicitly ignoring this
							break;
						case "Host":
							dest.Host = src.Host;
							break;
						case "If-Modified-Since":
							dest.IfModifiedSince = src.IfModifiedSince;
							break;
						case "Range":
							throw new NotSupportedException("Range copying isn't supported at this stage, we don't support range queries anyway, so it shouldn't matter");
						case "Referer":
							dest.Referer = src.Referer;
							break;
						case "Transfer-Encoding":
							dest.SendChunked = src.SendChunked;
							break;
						case "User-Agent":
							dest.UserAgent = src.UserAgent;
							break;
						case "Proxy-Connection":
							dest.Proxy = src.Proxy;
							break;
						default:
							throw new ArgumentException(string.Format("No idea how to handle restricted header: '{0}'", header));
					}
				}
				else
				{
					foreach (var value in values)
					{
						dest.Headers[header] = value;
					}
				}
			}
		}
Beispiel #6
1
 private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response,
     ref Stream responseStream, ref StreamReader reader)
 {
     if (request != null)
     {
         request = null;
     }
     if (response != null)
     {
         response.Close();
         response = null;
     }
     if (responseStream != null)
     {
         responseStream.Close();
         responseStream.Dispose();
         responseStream = null;
     }
     if (reader != null)
     {
         reader.Close();
         reader.Dispose();
         reader = null;
     }
 }
        private static HttpWebResponse PostForm(HttpWebRequest request , string userAgent, string contentType, byte[] formData)
        {
            if (request == null)
            {
                throw new NullReferenceException("request is not a http request");
            }

            // Set up the request properties.
            request.Method = "POST";
            request.ContentType = contentType;
            request.UserAgent = userAgent;
            request.CookieContainer = new CookieContainer();
            request.ContentLength = formData.Length;

            // You could add authentication here as well if needed:
            // request.PreAuthenticate = true;
            // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
            // request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));

            // Send the form data to the request.
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(formData, 0, formData.Length);
                requestStream.Close();
            }

            return request.GetResponse() as HttpWebResponse;
        }
Beispiel #8
1
        public void SendRequest(HttpWebRequest request)
        {
            int index = 0, size = 0;
            byte[][] data = new byte[Count * 2][];
            foreach (string key in AllKeys)
            {
                data[index] = HttpUtility.UrlEncodeToBytes(key);
                size += data[index++].Length;

                data[index] = HttpUtility.UrlEncodeToBytes(this[key]);
                size += data[index++].Length;
            }

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = size + Count * 2 - 1;

            using (Stream requestStream = request.GetRequestStream())
            {
                for (int i = 0; i < data.Length; i++)
                {
                    byte[] buff = data[i];
                    requestStream.Write(buff, 0, buff.Length);
                    if (i < data.Length - 1)
                        requestStream.WriteByte(SeparatorBytes[i % 2]);
                }
            }
        }
Beispiel #9
1
 public static void Download()
 {
     using (WebClient wcDownload = new WebClient())
     {
         try
         {
             webRequest = (HttpWebRequest)WebRequest.Create(optionDownloadURL);
             webRequest.Credentials = CredentialCache.DefaultCredentials;
             webResponse = (HttpWebResponse)webRequest.GetResponse();
             Int64 fileSize = webResponse.ContentLength;
             strResponse = wcDownload.OpenRead(optionDownloadURL);
             strLocal = new FileStream(optionDownloadPath, FileMode.Create, FileAccess.Write, FileShare.None);
             int bytesSize = 0;
             byte[] downBuffer = new byte[2048];
             downloadForm.Refresh();
             while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
             {
                 strLocal.Write(downBuffer, 0, bytesSize);
                 PercentProgress = Convert.ToInt32((strLocal.Length * 100) / fileSize);
                 pBar.Value = PercentProgress;
                 pLabel.Text = "Downloaded " + strLocal.Length + " out of " + fileSize + " (" + PercentProgress + "%)";
                 downloadForm.Refresh();
             }
         }
         catch { }
         finally
         {
             webResponse.Close();
             strResponse.Close();
             strLocal.Close();
             extractAndCleanup();
             downloadForm.Hide();
         }
     }
 }
        public string Create(string url)
        {
            try
            {
                // setup web request to tinyurl
                request = (HttpWebRequest)WebRequest.Create(string.Format(TINYURL_ADDRESS_TEMPLATE, url));
                request.Timeout = REQUEST_TIMEOUT;
                request.UserAgent = USER_AGENT;

                // get response
                response = (HttpWebResponse)request.GetResponse();

                // prase response stream to string
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(ENCODING_NAME));

                // convert the buffer into string and store in content
                StringBuilder sb = new StringBuilder();
                while (reader.Peek() >= 0)
                {
                    sb.Append(reader.ReadLine());
                }
                return sb.ToString();
            }
            catch (Exception)
            {
                return null;
            }
        }
Beispiel #11
1
		public WebConnection GetConnection (HttpWebRequest request)
		{
			WebConnection cnc = null;
			lock (connections) {
				WeakReference cncRef = null;

				// Remove disposed connections
				int end = connections.Count;
				ArrayList removed = null;
				for (int i = 0; i < end; i++) {
					cncRef = (WeakReference) connections [i];
					cnc = cncRef.Target as WebConnection;
					if (cnc == null) {
						if (removed == null)
							removed = new ArrayList (1);

						removed.Add (i);
					}
				}

				if (removed != null) {
					for (int i = removed.Count - 1; i >= 0; i--)
						connections.RemoveAt ((int) removed [i]);
				}

				cnc = CreateOrReuseConnection (request);
			}

			return cnc;
		}
Beispiel #12
1
        protected void UpdateCookies(string jScriptBody, HttpWebRequest request)
        {
            int setCookieIndex = -1;
            while ((setCookieIndex = jScriptBody.IndexOf("setCookie('")) != -1)
            {
                jScriptBody = jScriptBody.Substring(setCookieIndex + 11);
                string cookieName = jScriptBody.GetParent("'");

                string cookieValue = jScriptBody.GetChild(",", ',').Trim();
                if (!cookieValue.StartsWith("'"))
                {
                    switch (cookieValue)
                    {
                        case "document.referrer":
                        cookieValue = request.Referer;
                        break;
                    }
                }
                else cookieValue = cookieValue.GetChild("'", '\'');

                if (cookieValue != null)
                    cookieValue = Uri.EscapeDataString(cookieValue);

                string cookieObject =
                    (cookieName + "=" + cookieValue);

                Cookies.SetCookies(request.RequestUri, cookieObject);
            }
        }
        /// <summary>
        /// Signs the specified HTTP request with a shared key.
        /// </summary>
        /// <param name="request">The HTTP request to sign.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param>
        public void SignRequest(HttpWebRequest request, OperationContext operationContext)
        {
            CommonUtility.AssertNotNull("request", request);

            if (!request.Headers.AllKeys.Contains(Constants.HeaderConstants.Date, StringComparer.Ordinal))
            {
                string dateString = HttpWebUtility.ConvertDateTimeToHttpString(DateTime.UtcNow);
                request.Headers.Add(Constants.HeaderConstants.Date, dateString);
            }

            if (this.credentials.IsSharedKey)
            {
                string message = this.canonicalizer.CanonicalizeHttpRequest(request, this.accountName);
                Logger.LogVerbose(operationContext, SR.TraceStringToSign, message);

                StorageAccountKey accountKey = this.credentials.Key;
                string signature = CryptoUtility.ComputeHmac256(accountKey.KeyValue, message);

                if (!string.IsNullOrEmpty(accountKey.KeyName))
                {
                    request.Headers.Add(Constants.HeaderConstants.KeyNameHeader, accountKey.KeyName);
                }

                request.Headers.Add(
                    "Authorization",
                    string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", this.canonicalizer.AuthorizationScheme, this.credentials.AccountName, signature));
            }
        }
Beispiel #14
1
        /// <summary>
        /// Basic Authorization Header
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public CouchRequest(string uri, string username, string password)
        {
            request = (HttpWebRequest)WebRequest.Create(uri);
            request.Headers.Clear(); //important

            // Deal with Authorization Header
            if (username != null)
            {
                string authValue = "Basic ";
                string userNAndPassword = username + ":" + password;

                // Base64 encode
                string b64 = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(userNAndPassword));

                authValue = authValue + b64;

                request.Headers.Add("Authorization", authValue);
            }

            request.Headers.Add("Accept-Charset", "utf-8");
            request.Headers.Add("Accept-Language", "en-us");
            request.ContentType = "application/json";
            request.KeepAlive = true;
            request.Timeout = 10000;
        }
Beispiel #15
1
        public static string GerarArquivo(string texto)
        {
            Uri url = new Uri(string.Concat(URL_TTS_GOOGLE, texto));

            _request = (HttpWebRequest)HttpWebRequest.Create(url);
            _request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
            _request.UseDefaultCredentials = true;
           
            if (!string.IsNullOrEmpty(ProxyPath))
            {
                _request.Proxy = WebRequest.GetSystemWebProxy();
                _request.Proxy.Credentials = new NetworkCredential(ProxyUserName, ProxyPassword, ProxyDomain);
            }

            WebResponse response = _request.GetResponse();
            Stream fileContent = response.GetResponseStream();
            caminhoTemp = Path.ChangeExtension(Path.GetTempFileName(), ".mp3");

            using (Stream file = File.OpenWrite(caminhoTemp))
            {
                CopyStream(fileContent, file);
                file.Flush();
                file.Close();
            }

            fileContent.Close();
            fileContent.Dispose();

            return caminhoTemp;
        }
		public WebConnectionStream (WebConnection cnc, WebConnectionData data)
		{          
			if (data == null)
				throw new InvalidOperationException ("data was not initialized");
			if (data.Headers == null)
				throw new InvalidOperationException ("data.Headers was not initialized");
			if (data.request == null)
				throw new InvalidOperationException ("data.request was not initialized");
			isRead = true;
			cb_wrapper = new AsyncCallback (ReadCallbackWrapper);
			pending = new ManualResetEvent (true);
			this.request = data.request;
			read_timeout = request.ReadWriteTimeout;
			write_timeout = read_timeout;
			this.cnc = cnc;
			string contentType = data.Headers ["Transfer-Encoding"];
			bool chunkedRead = (contentType != null && contentType.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
			string clength = data.Headers ["Content-Length"];
			if (!chunkedRead && clength != null && clength != "") {
				try {
					contentLength = Int32.Parse (clength);
					if (contentLength == 0 && !IsNtlmAuth ()) {
						ReadAll ();
					}
				} catch {
					contentLength = Int64.MaxValue;
				}
			} else {
				contentLength = Int64.MaxValue;
			}

			// Negative numbers?
			if (!Int32.TryParse (clength, out stream_length))
				stream_length = -1;
		}
        private string RunResponse(HttpWebRequest request)
        {
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException wex)
            {
                if (wex.Response == null)
                    return JSON_ERROR;

                using (var errorResponse = (HttpWebResponse)wex.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        return reader.ReadToEnd(); //expected error from JSON
                    }
                }
            }

            var retVal = new StreamReader(stream: response.GetResponseStream()).ReadToEnd();

            return retVal;
        }
        public virtual HttpWebResponse GetHttpWebResp(HttpWebRequest webReq)
        {
            var countTry = 20;
              var repeat = true;
              HttpWebResponse res = null;
              while (repeat && countTry > 0)
            try
            {
              res = (HttpWebResponse)webReq.GetResponse();
              repeat = false;
            }
            catch (WebException wex)
            {
              countTry--;
              File.AppendAllText("log.txt", wex.Message + Environment.NewLine);
              File.AppendAllText("log.txt", "++" + Environment.NewLine);
              File.AppendAllText("log.txt", wex.Status.ToString() + Environment.NewLine);
              File.AppendAllText("log.txt", "++" + Environment.NewLine);
              File.AppendAllText("log.txt", "GetHttpWebResp" + Environment.NewLine);
              File.AppendAllText("log.txt", "------" + Environment.NewLine);
              webReq = GetHttpWebReq(url);
            }

              return res;
        }
		public MultipartRequest (GoogleConnection conn, string url)
		{
			request = conn.AuthenticatedRequest (url);
			request.Method = "POST";
			request.ContentType = "multipart/related; boundary=\"" + separator_string + "\"";
			request.Headers.Add ("MIME-version", "1.0");
		}
Beispiel #20
0
        private Result RequestAndRespond(HttpWebRequest request, string content)
        {
            HttpStatusCode statusCode = HttpStatusCode.NotFound;

            try
            {
                var contentBytes = Encoding.UTF8.GetBytes(content);
                request.ContentLength = contentBytes.Length;
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(contentBytes, 0, contentBytes.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    statusCode = HttpClient.GetStatusCode(response);
                }
            }
            catch (WebException webException)
            {
                var response = webException.Response as HttpWebResponse;
                statusCode = HttpClient.GetStatusCode(response);
            }

            return HttpStatusCodeExtensions.ToResult(statusCode);
        }
Beispiel #21
0
 public static HttpWebResponse GetResponse(HttpWebRequest request)
 {
     Contract.Requires(request != null);
     Debug.WriteLine("Request: " + request.RequestUri);
     var response = request.GetResponse() as HttpWebResponse;
     return response;
 }
Beispiel #22
0
 public RequestState()
 {
     BufferRead = new byte[BUFFER_SIZE];
     requestData = new StringBuilder(string.Empty);
     request = null;
     streamResponse = null;
 }
        public static void DateHeader(HttpWebRequest request, bool required)
        {
            bool standardHeader = request.Headers[HttpRequestHeader.Date] != null;
            bool msHeader = request.Headers["x-ms-date"] != null;

            Assert.IsFalse(standardHeader && msHeader);
            Assert.IsFalse(required && !(standardHeader ^ msHeader));

            if (request.Headers[HttpRequestHeader.Date] != null)
            {
                try
                {
                    DateTime parsed = DateTime.Parse(request.Headers[HttpRequestHeader.Date]).ToUniversalTime();
                }
                catch (Exception)
                {
                    Assert.Fail();
                }
            }
            else if (request.Headers[HttpRequestHeader.Date] != null)
            {
                try
                {
                    DateTime parsed = DateTime.Parse(request.Headers["x-ms-date"]).ToUniversalTime();
                }
                catch (Exception)
                {
                    Assert.Fail();
                }
            }
        }
 protected override void ProcessHttpWebRequest(HttpWebRequest httpWebRequest)
 {
     if (this.ReadWriteTimeout.HasValue)
     {
         httpWebRequest.ReadWriteTimeout = (int)this.ReadWriteTimeout.Value.TotalMilliseconds;
     }
 }
		public void ConfigureRequest(RavenConnectionStringOptions options, HttpWebRequest request)
		{
			if (RequestTimeoutInMs.HasValue)
				request.Timeout = RequestTimeoutInMs.Value;

			if (AllowWriteStreamBuffering.HasValue)
			{
				request.AllowWriteStreamBuffering = AllowWriteStreamBuffering.Value;
				if(AllowWriteStreamBuffering.Value == false)
					request.SendChunked = true;
			}

			if (options.ApiKey == null)
			{
				request.Credentials = options.Credentials ?? CredentialCache.DefaultNetworkCredentials;
				return;
			}

			var webRequestEventArgs = new WebRequestEventArgs { Request = request, Credentials = new OperationCredentials(options.ApiKey, options.Credentials)};

			AbstractAuthenticator existingAuthenticator;
			if (authenticators.TryGetValue(GetCacheKey(options), out existingAuthenticator))
			{
				existingAuthenticator.ConfigureRequest(this, webRequestEventArgs);
			}
			else
			{
				var basicAuthenticator = new BasicAuthenticator(enableBasicAuthenticationOverUnsecuredHttp: false);
				var securedAuthenticator = new SecuredAuthenticator();

				basicAuthenticator.ConfigureRequest(this, webRequestEventArgs);
				securedAuthenticator.ConfigureRequest(this, webRequestEventArgs);
			}
		}
        public HttpWebResponse ExecuteRequest(HttpWebRequest request)
        {
            try
            {
                if (this.BeforeRequest != null)
                    this.BeforeRequest(request);

                var response = (HttpWebResponse)request.GetResponse();

                if (this.AfterResponse != null)
                    this.AfterResponse(response);

                return response;
            }
            catch (WebException ex)
            {
                throw WebRequestException.CreateFromWebException(ex);
            }
            catch (AggregateException ex)
            {
                if (ex.InnerException is WebException)
                {
                    throw WebRequestException.CreateFromWebException(ex.InnerException as WebException);
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #27
0
        public override void SetAuth(HttpWebRequest request, Stream body)
        {
            byte[] secretKey = Encoding.ASCII.GetBytes(Config.SECRET_KEY);
            using (HMACSHA1 hmac = new HMACSHA1(secretKey))
            {
                string pathAndQuery = request.Address.PathAndQuery;
                byte[] pathAndQueryBytes = Encoding.ASCII.GetBytes(pathAndQuery);
                using (MemoryStream buffer = new MemoryStream())
                {
                    buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length);
                    buffer.WriteByte((byte)'\n');
                    if (request.ContentType == "application/x-www-form-urlencoded" && body != null)
                    {
                        if (!body.CanSeek)
                        {
                            throw new Exception("stream can not seek");
                        }
                        StreamUtil.Copy(body, buffer);
                        body.Seek(0, SeekOrigin.Begin);
                    }
                    byte[] digest = hmac.ComputeHash(buffer.ToArray());
                    string digestBase64 = Base64UrlSafe.Encode(digest);

                    string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64;
                    request.Headers.Add("Authorization", authHead);
                }
            }
        }
Beispiel #28
0
		internal HttpJsonRequest(
			CreateHttpJsonRequestParams requestParams,
			HttpJsonRequestFactory factory)
		{
			Url = requestParams.Url;
			this.factory = factory;
			owner = requestParams.Owner;
			conventions = requestParams.Convention;
			Method = requestParams.Method;
			webRequest = (HttpWebRequest)WebRequest.Create(requestParams.Url);
			webRequest.UseDefaultCredentials = true;
			webRequest.Credentials = requestParams.Credentials;
			webRequest.Method = requestParams.Method;
			if (factory.DisableRequestCompression == false && requestParams.DisableRequestCompression == false)
			{
				if (requestParams.Method == "POST" || requestParams.Method == "PUT" ||
					requestParams.Method == "PATCH" || requestParams.Method == "EVAL")
					webRequest.Headers["Content-Encoding"] = "gzip";

				webRequest.Headers["Accept-Encoding"] = "gzip";
			}
			webRequest.ContentType = "application/json; charset=utf-8";
			webRequest.Headers.Add("Raven-Client-Version", ClientVersion);
			WriteMetadata(requestParams.Metadata);
			requestParams.UpdateHeaders(webRequest);
		}
        private static async Task<string> GetResponseStringFromRequest(HttpWebRequest request)
        {
            try
            {
                using (var response = await request.GetResponseAsync()
                                                .ConfigureAwait(false))
                {
                    return GetResponseString(response);
                }
            }
            catch (WebException e)
            {
                using (var response = e.Response.GetResponseStream())
                {
                    if (response == null)
                    {
                        throw;
                    }
                    JObject responseItem;
                    try
                    {
                        responseItem = JObject.Load(new JsonTextReader(new StreamReader(response)));
                    }
                    catch (Exception)
                    {
                        throw e;
                    }
                    ThrowIfIsException(responseItem);

                    throw;
                }
            }
        }
Beispiel #30
0
 /// <summary>
 /// TOP API POST 请求
 /// </summary>
 /// <param name="url">请求容器URL</param>
 /// <param name="appkey">AppKey</param>
 /// <param name="appSecret">AppSecret</param>
 /// <param name="method">API接口方法名</param>
 /// <param name="session">调用私有的sessionkey</param>
 /// <param name="param">请求参数</param>
 /// <returns>返回字符串</returns>
 public static string Post(string url, string appkey, string appSecret, string method, string session,
                           IDictionary <string, string> param)
 {
     #region -----API系统参数----
     param.Add("app_key", appkey);
     param.Add("method", method);
     param.Add("session", session);
     param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
     param.Add("format", "xml");
     param.Add("v", "2.0");
     param.Add("sign_method", "md5");
     param.Add("sign", CreateSign(param, appSecret));
     #endregion
     string result = string.Empty;
     #region ---- 完成 HTTP POST 请求----
     System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
     req.Method      = "POST";
     req.KeepAlive   = true;
     req.Timeout     = 300000;
     req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
     byte[] postData  = Encoding.UTF8.GetBytes(PostData(param));
     Stream reqStream = req.GetRequestStream();
     reqStream.Write(postData, 0, postData.Length);
     reqStream.Close();
     System.Net.HttpWebResponse rsp = (System.Net.HttpWebResponse)req.GetResponse();
     Encoding     encoding          = Encoding.GetEncoding(rsp.CharacterSet);
     Stream       stream            = null;
     StreamReader reader            = null;
     stream = rsp.GetResponseStream();
     reader = new StreamReader(stream, encoding);
     result = reader.ReadToEnd();
     if (reader != null)
     {
         reader.Close();
     }
     if (stream != null)
     {
         stream.Close();
     }
     if (rsp != null)
     {
         rsp.Close();
     }
     #endregion
     return(Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", ""));
 }
Beispiel #31
0
    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="URL">文件URL</param>
    /// <param name="filename">保存到本地名称(如:D:\App\App.exe)</param>
    /// <param name="prog">进度条控件名</param>
    /// <param name="label1">显示进度文字控件</param>
    /// <returns></returns>
    public static string DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
    {
        string result  = "下载失败";
        float  percent = 0;

        try
        {
            System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
            System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
            long totalBytes = myrp.ContentLength;
            if (prog != null)
            {
                prog.Maximum = (int)totalBytes;
            }
            System.IO.Stream st = myrp.GetResponseStream();
            System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
            long             totalDownloadedByte = 0;
            byte[]           by = new byte[1024];
            int osize           = st.Read(by, 0, (int)by.Length);
            while (osize > 0)
            {
                totalDownloadedByte = osize + totalDownloadedByte;
                System.Windows.Forms.Application.DoEvents();
                so.Write(by, 0, osize);
                if (prog != null)
                {
                    prog.Value = (int)totalDownloadedByte;
                }
                osize = st.Read(by, 0, (int)by.Length);

                percent     = (float)totalDownloadedByte / (float)totalBytes * 100;
                label1.Text = "下载进度:" + percent.ToString() + "%";
                System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
            }
            so.Close();
            st.Close();
            result = "";
        }
        catch (System.Exception ex)
        {
            result = "下载失败:" + ex.Message;
        }
        return(result);
    }
Beispiel #32
0
    IEnumerator tickCoroutine()
    {
        Dictionary <String, String> eventsMap = initMap();

        while (true)
        {
//			sendMessage("event1");
            // do stuff here
//			Debug.Log( "some string in the console " + Time.time);

//			GameObject.FindObjectOfType<ServerMessage>().doSomething();

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://vr-jam.herokuapp.com/listen");
            var response = request.GetResponse();
            var sr       = new System.IO.StreamReader(response.GetResponseStream());

            var message = sr.ReadToEnd();

            Debug.Log("GOT MESSAGE: " + message);

            if (!String.IsNullOrEmpty(message))
            {
                var elements = message.Split('|');
                if (elements.Length == 3)
                {
                    var states = elements[0] + "|" + elements[1];

                    string value;
                    if (eventsMap.TryGetValue(states, out value))
                    {
                        sendMessage(value);
//						PlayMakerFSM.BroadcastEvent("continue");
                        return(true);
                    }
                }
            }

            // done checking, now wait 0.1 seconds
            yield return(new WaitForSeconds(1f));
        }
    }
Beispiel #33
0
        /// <summary> 检测WebService是否可用 </summary>
        public static bool IsWebServiceAvaiable(string url)
        {
            bool bRet = false;

            Net.HttpWebRequest myHttpWebRequest = null;
            try
            {
                System.GC.Collect();

                myHttpWebRequest           = (Net.HttpWebRequest)Net.WebRequest.Create(url);
                myHttpWebRequest.Timeout   = 60000;
                myHttpWebRequest.KeepAlive = false;
                myHttpWebRequest.ServicePoint.ConnectionLimit = 200;
                using (Net.HttpWebResponse myHttpWebResponse = (Net.HttpWebResponse)myHttpWebRequest.GetResponse())
                {
                    bRet = true;
                    if (myHttpWebResponse != null)
                    {
                        myHttpWebResponse.Close();
                    }
                }
            }
            catch (Net.WebException e)
            {
                Common.LogHelper.Instance.WriteError(String.Format("网络连接错误 : {0}", e.Message));
            }
            catch (Exception ex)
            {
                Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace);
            }
            finally
            {
                if (myHttpWebRequest != null)
                {
                    myHttpWebRequest.Abort();
                    myHttpWebRequest = null;
                }
            }

            return(bRet);
        }
    public WolframAlphaValidationResult ValidateQuery(WolframAlphaQuery Query)
    {
        if (Query.APIKey == "")
        {
            if (this.APIKey == "")
            {
                throw new Exception("To use the Wolfram Alpha API, you must specify an API key either through the parsed WolframAlphaQuery, or on the WolframAlphaEngine itself.");
            }
            Query.APIKey = this.APIKey;
        }

        if (Query.Asynchronous == true && Query.Format == WolframAlphaQuery.WolframAlphaQueryFormat.HTML)
        {
            throw new Exception("Wolfram Alpha does not allow asynchronous operations while the format for the query is not set to \"HTML\".");
        }
        System.Net.HttpWebRequest WebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://preview.wolframalpha.com/api/v1/validatequery.jsp" + Query.FullQueryString);
        WebRequest.KeepAlive = true;
        string Response = new StreamReader(WebRequest.GetResponse().GetResponseStream()).ReadToEnd();

        return(ValidateQuery(Response));
    }
Beispiel #35
0
 /// <summary>
 /// Http Get 获取网页内容
 /// </summary>
 /// <param name="TheURL">url</param>
 /// <returns></returns>
 public static string GetUrlData(string TheURL)
 {
     try
     {
         Uri uri = new Uri(TheURL);
         System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
         request.Method            = "GET";
         request.ContentType       = "application/x-www-form-urlencoded";
         request.AllowAutoRedirect = false;
         request.Timeout           = 5000;
         System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
         Stream       responseStream         = response.GetResponseStream();
         StreamReader readStream             = new StreamReader(responseStream, System.Text.Encoding.UTF8);
         string       retext = readStream.ReadToEnd().ToString();
         readStream.Close();
         return(retext);
     }
     catch (Exception ex)
     {
         return(ex.ToString());
     }
 }
Beispiel #36
0
    public static string Recharge_Bal(string MobileNo, decimal amt, string rcode, string transid)
    {
        try
        {
            string output = "";

            System.Net.HttpWebRequest  request  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.simpleapi.in/recharge.ashx?uid=7893123555&pwd=12345&mobileno=" + MobileNo + "&amt=" + amt + "&rcode=" + rcode + "&transid=" + transid + "");
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                string text = sr.ReadToEnd();
                output = text;
                DataSet objDataSet1 = MasterCode.RetrieveQuery("update Request set  ResponseCode= '" + text.ToString() + "' where ClientTXT='" + transid + "'");
            }

            return(output);//SqlHelper.ExecuteDataset(con, CommandType.StoredProcedure, "Sp_Offers", objSqlParameter);
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }
Beispiel #37
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string username         = "******";
        string password         = "******";
        string usernamePassword = username + ":" + password;

        string url        = "http://api.t.sina.com.cn/statuses/update.json";
        string news_title = "VS2010网剧合集:讲述程序员的爱情故事";
        int    news_id    = 62747;
        string t_news     = string.Format("{0},http://news.cnblogs.com/n/{1}/", news_title, news_id);
        string data       = "source=3854961754&status=" + System.Web.HttpUtility.UrlEncode(t_news);

        System.Net.WebRequest     webRequest  = System.Net.WebRequest.Create(url);
        System.Net.HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest;

        System.Net.CredentialCache myCache = new System.Net.CredentialCache();
        myCache.Add(new Uri(url), "Basic", new System.Net.NetworkCredential(username, password));
        httpRequest.Credentials = myCache;
        httpRequest.Headers.Add("Authorization", "Basic " +
                                Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(usernamePassword)));


        httpRequest.Method      = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        System.Text.Encoding encoding = System.Text.Encoding.ASCII;
        byte[] bytesToPost            = encoding.GetBytes(data);
        httpRequest.ContentLength = bytesToPost.Length;
        System.IO.Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytesToPost, 0, bytesToPost.Length);
        requestStream.Close();

        System.Net.WebResponse wr            = httpRequest.GetResponse();
        System.IO.Stream       receiveStream = wr.GetResponseStream();
        using (System.IO.StreamReader reader = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8))
        {
            string responseContent = reader.ReadToEnd();
            Response.Write(responseContent);
        }
    }
Beispiel #38
0
 public static bool UrlExist(string url)
 {
     System.Net.HttpWebRequest wreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
     wreq.Method  = "GET";
     wreq.Timeout = 3000;
     System.Net.HttpWebResponse wr;
     try
     {
         wr = (System.Net.HttpWebResponse)wreq.GetResponse();
         if (wr.StatusCode == System.Net.HttpStatusCode.OK)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch
     {
         return(false);
     }
 }
        private string PerformLogin(string password, string nonce)
        {
            var httpOptions = new Duplicati.Library.Modules.Builtin.HttpOptions();

            httpOptions.Configure(m_options);

            using (httpOptions)
            {
                System.Net.HttpWebRequest req =
                    (System.Net.HttpWebRequest)System.Net.WebRequest.Create(m_baseUri + LOGIN_SCRIPT);
                req.Method    = "POST";
                req.UserAgent = "Duplicati TrayIcon Monitor, v" +
                                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                req.Headers.Add(TRAYICONPASSWORDSOURCE_HEADER, m_TrayIconHeaderValue);
                req.ContentType = "application/x-www-form-urlencoded";
                if (req.CookieContainer == null)
                {
                    req.CookieContainer = new System.Net.CookieContainer();
                }
                req.CookieContainer.Add(new System.Net.Cookie("session-nonce", nonce, "/", req.RequestUri.Host));

                //Wrap it all in async stuff
                Duplicati.Library.Utility.AsyncHttpRequest areq = new Library.Utility.AsyncHttpRequest(req);
                var body = System.Text.Encoding.ASCII.GetBytes("password=" +
                                                               Duplicati.Library.Utility.Uri.UrlEncode(password));
                using (var f = areq.GetRequestStream(body.Length))
                    f.Write(body, 0, body.Length);

                using (var r = (System.Net.HttpWebResponse)areq.GetResponse())
                    if (r.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        return((r.Cookies[AUTH_COOKIE] ?? r.Cookies[Library.Utility.Uri.UrlEncode(AUTH_COOKIE)]).Value);
                    }

                return(null);
            }
        }
Beispiel #40
0
        /// <summary>
        /// 读取页面内容
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encodingType"></param>
        /// <returns></returns>
        public static string HttpGet(string strUrl, string encodingType)
        {
            try
            {
                StringBuilder             dataReturnString = new StringBuilder();
                Stream                    dataStream;
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(strUrl);
                req.Method  = "GET";
                req.Timeout = 6000;
                req.AllowWriteStreamBuffering = true;
                req.AllowAutoRedirect         = true;
                System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();

                if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    dataStream = resp.GetResponseStream();
                    System.Text.Encoding encode     = System.Text.Encoding.GetEncoding(encodingType);
                    StreamReader         readStream = new StreamReader(dataStream, encode);
                    char[] cCount = new char[500];
                    int    count  = readStream.Read(cCount, 0, 256);
                    while (count > 0)
                    {
                        String str = new String(cCount, 0, count);
                        dataReturnString.Append(str);
                        count = readStream.Read(cCount, 0, 256);
                    }
                    resp.Close();
                    return(dataReturnString.ToString());
                }
                resp.Close();
                return(null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #41
0
        public void Put(string remotename, string filename)
        {
            string endpoint = "";
            string siafile  = m_targetpath + "/" + remotename;

            try {
                endpoint = string.Format("/renter/upload/{0}/{1}?source={2}",
                                         m_targetpath,
                                         Library.Utility.Uri.UrlEncode(remotename).Replace("+", "%20"),
                                         Library.Utility.Uri.UrlEncode(filename).Replace("+", "%20")
                                         );

                System.Net.HttpWebRequest req = CreateRequest(endpoint);
                req.Method = System.Net.WebRequestMethods.Http.Post;

                Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);

                using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse())
                {
                    int code = (int)resp.StatusCode;
                    if (code < 200 || code >= 300)
                    {
                        throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp);
                    }

                    while (!IsUploadComplete(siafile))
                    {
                        System.Threading.Thread.Sleep(5000);
                    }
                }
            }
            catch (System.Net.WebException wex)
            {
                throw new Exception(getResponseBodyOnError(endpoint, wex));
            }
        }
Beispiel #42
0
        public static string GetIP()
        {
            Uri uri = new Uri("http://www.ikaka.com/ip/index.asp");

            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
            req.Method          = "POST";
            req.ContentType     = "application/x-www-form-urlencoded";
            req.ContentLength   = 0;
            req.CookieContainer = new System.Net.CookieContainer();
            req.GetRequestStream().Write(new byte[0], 0, 0);
            System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)(req.GetResponse());
            StreamReader rs = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("GB18030"));
            string       s  = rs.ReadToEnd();

            rs.Close();
            req.Abort();
            res.Close();
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, @"IP:\[(?<IP>[0-9\.]*)\]");
            if (m.Success)
            {
                return(m.Groups["IP"].Value);
            }
            return(string.Empty);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         Session["update_day"] = DateTime.Now.ToString();
         ListBox1.Items.Clear();
         ListBox2.Items.Clear();
         //very first load//
         Session["count_sec"] = "1";
         //main
         int    total_count = 0;
         string oauthUrl1   = string.Format("http://gws.gnavi.co.jp/gws/RestSearchAPI/ver2.0/?keyid=key&pref=PREF13&format=json");
         string results1    = String.Empty;
         System.Net.HttpWebRequest request1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(oauthUrl1);
         using (var response1 = request1.GetResponse())
             using (System.IO.StreamReader sr = new System.IO.StreamReader(response1.GetResponseStream()))
             {
                 results1 = sr.ReadToEnd();
             }
         if (results1 != "")
         {
             Newtonsoft.Json.Linq.JObject jArray1 = Newtonsoft.Json.Linq.JObject.Parse(results1);
             total_count = (int)jArray1["total_hit_count"];
         }
         //Facebook.FacebookClient myfacebook = new Facebook.FacebookClient();
         int count = 20;
         int dev   = (total_count / count) + 1;
         Session["count_max"] = dev.ToString();
     }
     if (Session["seak"] != null)
     {
         if (Session["seak"].ToString() == "true")
         {
         }
     }
 }
        public static JsonToAbject ReturnGoodsInterface(string orderId, int type)
        {
            SetFlagValue(type);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            //参数
            IDictionary <string, string> parameters = new Dictionary <string, string>();
            string timestamp, token;

            SetBaseInterfcaeParameters(out timestamp, out token);
            parameters.Add("method", nameof(invalidOrders));
            parameters.Add("flag", flag);
            parameters.Add("model", invalidOrders);
            DataMain data_main = new DataMain()
            {
                order_id  = orderId,
                token     = token,
                timestamp = timestamp,
            };
            string       Data_Json = SetParametersJson(parameters, data_main);
            string       jsonString = HttpRequestHelper.PostPage(strURL, Data_Json);
            JsonToAbject jsonToAbject = HttpRequestHelper.JsonToObject <JsonToAbject>(jsonString);

            return(jsonToAbject);
        }
Beispiel #45
0
        /// <summary>
        /// Cria a stream com os parametros para a requisição.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private System.Net.HttpWebRequest CreateStreamRequest(Colosoft.Net.IUploaderItem item)
        {
            byte[] buffer   = new byte[1024];
            int    read     = 0;
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            System.Net.HttpWebRequest request = CreateRequest(Url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method      = "POST";
            request.KeepAlive   = true;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            var info = new Colosoft.Net.UploaderItemInfo(item);

            using (var outputStream = GetRequestStream(item, request))
            {
                outputStream.Write(boundarybytes, 0, boundarybytes.Length);
                string header      = "Content-Disposition: form-data; name=\"info\";\r\nContent-Type:application/octet-stream\r\n\r\n";
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                outputStream.Write(headerbytes, 0, headerbytes.Length);
                var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Colosoft.Net.UploaderItemInfo));
                serializer.Serialize(outputStream, info);
                outputStream.Write(boundarybytes, 0, boundarybytes.Length);
                header      = "Content-Disposition: form-data; name=\"data\"; filename=\"item.data\"\r\nContent-Type:application/octet-stream\r\n\r\n";
                headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                outputStream.Write(headerbytes, 0, headerbytes.Length);
                using (var itemStream = item.GetContent())
                    while ((read = itemStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outputStream.Write(buffer, 0, read);
                    }
                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                outputStream.Write(trailer, 0, trailer.Length);
            }
            return(request);
        }
Beispiel #46
0
        public void Cancel()
        {
            this.completedCallback = null;
            this.errorCallback     = null;
            this.failedCallback    = null;

            if (timeoutTokenSource != null)
            {
                try
                {
                    timeoutTokenSource.Cancel();
                }
                catch (Exception) {};

                timeoutTokenSource.Dispose();
                timeoutTokenSource = null;
            }

            if (this.webRequest != null)
            {
                this.webRequest.Abort();
                this.webRequest = null;
            }
        }
        /// <summary>Create a HttpWebRequest object and setup to on general web servers.</summary>
        /// <param name="url">URL that will be used on the request.</param>
        /// <returns>HttpWebRequest setup to work on general web servers</returns>
        protected virtual System.Net.HttpWebRequest CreateHttpWebRequest(string url, Dictionary <string, string> getData = null, Dictionary <string, string> postData = null)
        {
            if (getData != null)
            {
                var firstParameter = true;

                foreach (var keyValuePair in getData)
                {
                    url           += firstParameter ? "?" : "&";
                    url           += string.Format("{0}={1}", keyValuePair.Key, HttpUtility.UrlEncode(keyValuePair.Value));
                    firstParameter = false;
                }
            }

            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

            httpWebRequest.UserAgent       = Properties.Settings.Default.Common_Collector_Request_UserAgent;
            httpWebRequest.Accept          = Properties.Settings.Default.Common_Collector_Request_Accept;
            httpWebRequest.CookieContainer = _cookieContainer;

            if (postData != null)
            {
                var postDataArray  = postData.Select(pd => string.Format("{0}={1}", pd.Key, HttpUtility.UrlEncode(pd.Value))).ToArray();
                var postDataString = string.Join("&", postDataArray.ToArray());

                var postDataStream = Encoding.UTF8.GetBytes(postDataString);

                httpWebRequest.Method        = "POST";
                httpWebRequest.ContentLength = postDataStream.Length;
                Stream httpWebRequestStream = httpWebRequest.GetRequestStream();
                httpWebRequestStream.Write(postDataStream, 0, postDataStream.Length);
                httpWebRequestStream.Close();
            }

            return(httpWebRequest);
        }
Beispiel #48
0
 /// <summary>
 /// c#,.net 下载文件
 /// </summary>
 /// http://localhost:8080/tomcat.zip
 /// <param name="URL">下载文件地址</param>
 ///
 /// <param name="Filename">下载后的存放地址</param>
 /// <param name="Prog">用于显示的进度条</param>
 ///
 public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog)
 {
     try
     {
         System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
         System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
         long totalBytes = myrp.ContentLength;
         if (prog != null)
         {
             prog.Maximum = (int)totalBytes;
         }
         System.IO.Stream st = myrp.GetResponseStream();
         System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
         long             totalDownloadedByte = 0;
         byte[]           by = new byte[1024];
         int osize           = st.Read(by, 0, (int)by.Length);
         while (osize > 0)
         {
             totalDownloadedByte = osize + totalDownloadedByte;
             System.Windows.Forms.Application.DoEvents();
             so.Write(by, 0, osize);
             if (prog != null)
             {
                 prog.Value = (int)totalDownloadedByte;
             }
             osize = st.Read(by, 0, (int)by.Length);
         }
         so.Close();
         st.Close();
     }
     catch (System.Exception)
     {
         MessageBox.Show("硬盘读写或者网络连接异常!!\n请检查你相关功能是否能正常使用!请稍后重试^_^~", "更新失败:");
         Application.Exit();
     }
 }
Beispiel #49
0
        public static byte[] GetImageFromUrl(string url, Dictionary <String, String> dictionary)
        {
            System.Net.HttpWebRequest  request  = null;
            System.Net.HttpWebResponse response = null;
            byte[] b = null;


            try
            {
                request  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                response = (System.Net.HttpWebResponse)request.GetResponse();

                if (request.HaveResponse)
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        Stream receiveStream = response.GetResponseStream();
                        using (BinaryReader br = new BinaryReader(receiveStream))
                        {
                            b = br.ReadBytes(500000);
                            br.Close();
                        }

                        foreach (var h in response.Headers.AllKeys)
                        {
                            dictionary.Add(h, response.Headers[h]);
                        }
                        dictionary.Add("ContentType", response.ContentType);
                    }
                }
            }
            catch (Exception)
            {
            }
            return(b);
        }
Beispiel #50
0
        //[ValidateAntiForgeryToken]
        public void SendSMS(List <string> to, string message, bool saveHistory = false)
        {
            try
            {
                smsResults.Clear();
                foreach (var item in to)
                {
                    //Uri targetUri = new Uri($"https://api.sabanovin.com/v1/{_SMSApiKey}/sms/send.json?gateway={_SMSProviderNumber}&to={item}&text={message}");
                    Uri targetUri = new Uri(_SMSApi);

                    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(targetUri);

                    request.Credentials = CredentialCache.DefaultCredentials;
                    // Get the response.
                    WebResponse response = request.GetResponse();
                    //HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
                }
            }
            catch (Exception)
            {
                // در صورتی که خروجی وب سرویس 200 نباشد این خطارخ می دهد.
                throw new NotImplementedException();
            }
        }
        public static bool AddFilterPreferencesToServer(string ip, DataModels.FilterDataModel fil)
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer _jsonSerializerForString =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string));
            string url = "http://localhost:5000/api/filterpreferences/";

            url += ip;
            System.Net.HttpWebRequest _httpPostReq =
                System.Net.WebRequest.CreateHttp(url);
            _httpPostReq.Method      = "POST";
            _httpPostReq.ContentType = "application/json";
            System.Runtime.Serialization.Json.DataContractJsonSerializer filterDataJsonSerializer =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(DataModels.FilterDataModel));
            filterDataJsonSerializer.WriteObject(_httpPostReq.GetRequestStream(), fil);
            System.Net.HttpWebResponse response = _httpPostReq.GetResponse() as HttpWebResponse;
            bool status = false;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                string status_in_string = _jsonSerializerForString.ReadObject(response.GetResponseStream()) as string;
                status = bool.Parse(status_in_string);
            }
            return(status);
        }
Beispiel #52
0
        /// <summary>
        /// 带进度的下载文件
        /// </summary>
        /// <param name="URL">下载文件地址</param>
        /// <param name="Filename">下载后的存放地址</param>
        ///
        public bool DownloadFileProg(string URL, string filename)
        {
            float percent = 0;

            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                this.prog_totalBytes = (int)totalBytes;
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[1024];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    this.prog_Value = (int)totalDownloadedByte;
                    osize           = st.Read(by, 0, (int)by.Length);

                    percent        = (float)totalDownloadedByte / (float)totalBytes * 100;
                    this.la_status = "当前下载进度" + percent.ToString() + "%";
                }
                so.Close();
                st.Close();
                return(true);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
Beispiel #53
0
        public void Delete(string remotename)
        {
            string endpoint = "";

            try
            {
                endpoint = string.Format("/renter/delete/{0}/{1}",
                                         m_targetpath,
                                         Library.Utility.Uri.UrlEncode(remotename).Replace("+", "%20")
                                         );
                System.Net.HttpWebRequest req = CreateRequest(endpoint);
                req.Method = System.Net.WebRequestMethods.Http.Post;

                Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);

                using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse())
                {
                    int code = (int)resp.StatusCode;
                    if (code < 200 || code >= 300)
                    {
                        throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp);
                    }
                }
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    throw new FileMissingException(wex);
                }
                else
                {
                    throw new Exception(getResponseBodyOnError(endpoint, wex));
                }
            }
        }
Beispiel #54
0
        public string PFPost(string postData)
        {
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
            Encoding encoding = Encoding.UTF8;

            byte[] data = encoding.GetBytes(postData.Trim());
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url);
            req.Method = "POST";
            //req.ContentType = "application/x-www-form-urlencoded";
            req.ContentType = "application/json";
            //req.ContentType = "text/html";

            req.ContentLength = data.Length;

            System.IO.Stream newStream = req.GetRequestStream();
            //发送数据
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse();
            StreamReader reader            = new StreamReader(res.GetResponseStream(), Encoding.UTF8);

            return(reader.ReadToEnd());
        }
Beispiel #55
0
        protected override void SetHttpRequestPostHeader(System.Net.HttpWebRequest httpRequest)
        {
            httpRequest.Method    = HttpHelperBase.MethodPost;
            httpRequest.Timeout   = HttpHelperBase.ConnectTimeout;
            httpRequest.KeepAlive = true;
            if (!isRedirected)
            {
                httpRequest.AllowAutoRedirect = false;
                //isRedirected = true;
            }
            else
            {
                httpRequest.AllowAutoRedirect = true;
            }

            httpRequest.CookieContainer = this.cookieContainer;
            httpRequest.Accept          = @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            httpRequest.UserAgent       = @"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11";
            httpRequest.ContentType     = @"application/x-www-form-urlencoded";
            httpRequest.ProtocolVersion = new Version("1.1");

            //httpRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us");
            httpRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8");
            httpRequest.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");//"no-cache"
            httpRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            httpRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "GBK,utf-8;q=0.7,*;q=0.3");
            this.SetCookieToHttpRequestHeader(httpRequest);
            this.SetProxy(httpRequest);
            httpRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };

            if ((null != httpRequest) && (!string.IsNullOrEmpty(this.refererUrl)))
            {
                httpRequest.Referer = this.refererUrl;
            }
        }
Beispiel #56
0
        private string Get_Http(string strUrl, int timeout)
        {
            string result;

            try
            {
                System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
                httpWebRequest.Timeout = timeout;
                System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
                System.IO.Stream           responseStream  = httpWebResponse.GetResponseStream();
                System.IO.StreamReader     streamReader    = new System.IO.StreamReader(responseStream, System.Text.Encoding.Default);
                System.Text.StringBuilder  stringBuilder   = new System.Text.StringBuilder();
                while (-1 != streamReader.Peek())
                {
                    stringBuilder.Append(streamReader.ReadLine());
                }
                result = stringBuilder.ToString();
            }
            catch (System.Exception ex)
            {
                result = "错误:" + ex.Message;
            }
            return(result);
        }
Beispiel #57
0
        public void DownloadFile(string URL, string filename, System.Windows.Forms.Label label1)
        {
            float percent = 0;

            try
            {
                System.Net.HttpWebRequest  Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;

                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long             totalDownloadedByte = 0;
                byte[]           by = new byte[10240];
                int osize           = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);

                    osize = st.Read(by, 0, (int)by.Length);

                    percent     = (float)totalDownloadedByte / (float)totalBytes * 100;
                    percent     = (float)Math.Round(percent, 3);
                    label1.Text = "当前下载进度:" + percent.ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                MessageBox.Show("下载失败,可能是网络问题");
            }
        }
Beispiel #58
0
        private SiaDownloadList GetDownloads()
        {
            var    fl       = new SiaDownloadList();
            string endpoint = string.Format("/renter/downloads");

            try
            {
                System.Net.HttpWebRequest req = CreateRequest(endpoint);
                req.Method = System.Net.WebRequestMethods.Http.Get;

                Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);

                using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse())
                {
                    int code = (int)resp.StatusCode;
                    if (code < 200 || code >= 300)
                    {
                        throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp);
                    }

                    var serializer = new JsonSerializer();

                    using (var rs = areq.GetResponseStream())
                        using (var sr = new System.IO.StreamReader(rs))
                            using (var jr = new Newtonsoft.Json.JsonTextReader(sr))
                            {
                                fl = (SiaDownloadList)serializer.Deserialize(jr, typeof(SiaDownloadList));
                            }
                }
            }
            catch (System.Net.WebException wex)
            {
                throw new Exception(getResponseBodyOnError(endpoint, wex));
            }
            return(fl);
        }
    private static string GetHTML(string URL)
    {
        string connectionString = URL;

        try
        {
            System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
            myRequest.Credentials = CredentialCache.DefaultCredentials;
            //// Get the response
            WebResponse webResponse = myRequest.GetResponse();
            Stream      respStream  = webResponse.GetResponseStream();
            ////
            StreamReader ioStream    = new StreamReader(respStream);
            string       pageContent = ioStream.ReadToEnd();
            //// Close streams
            ioStream.Close();
            respStream.Close();
            return(pageContent);
        }
        catch (Exception)
        {
        }
        return(null);
    }
Beispiel #60
-1
        /// <summary>
        /// Fetches the <see cref="scrape"/> after logging into the <see cref="url"/> with the specified <see cref="postdata"/>
        /// </summary>
        /// <param name="url">The URL to login at </param>
        /// <param name="postdata">The postdata to login with.</param>
        /// <param name="scrape">The page to scrape.</param>
        /// <returns>The fetched page</returns>
        private string GetPage(string url, string postdata, string scrape)
        {
            req = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookies = new CookieContainer();
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            req.CookieContainer = cookies;

            StreamWriter requestWriter = new StreamWriter(req.GetRequestStream());
            requestWriter.Write(postdata);
            requestWriter.Close();

            req.GetResponse();
            cookies = req.CookieContainer;

            req = WebRequest.Create(scrape) as HttpWebRequest;
            req.CookieContainer = cookies;

            StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream());

            string response = responseReader.ReadToEnd();
            responseReader.Close();

            return response;
        }