Inheritance: WebRequest, ISerializable
        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;
        }
Example #2
1
 private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
 {
     using (Stream stream = webRequest.GetRequestStream())
     {
         soapEnvelopeXml.Save(stream);
     }
 }
Example #3
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;
        }
        /// <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;
        }
Example #5
1
		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;
		}
        /// <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));
            }
        }
        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;
            }
        }
        /// <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;
        }
Example #9
1
	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;
				}
			}
		}
	}
Example #10
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();
         }
     }
 }
Example #11
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;
        }
Example #12
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;
        }
Example #13
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);
            }
        }
	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");
	}
Example #15
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;
		}
        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;
        }
Example #17
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]);
                }
            }
        }
Example #18
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;
     }
 }
 internal NonEntityOperationResult(object source, HttpWebRequest request, AsyncCallback callback, object state)
 {
   this.source = source;
   this.request = request;
   this.userCallback = callback;
   this.userState = state;
 }
Example #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);
        }
 protected override void ProcessHttpWebRequest(HttpWebRequest httpWebRequest)
 {
     if (this.ReadWriteTimeout.HasValue)
     {
         httpWebRequest.ReadWriteTimeout = (int)this.ReadWriteTimeout.Value.TotalMilliseconds;
     }
 }
Example #22
0
 public static HttpWebResponse GetResponse(HttpWebRequest request)
 {
     Contract.Requires(request != null);
     Debug.WriteLine("Request: " + request.RequestUri);
     var response = request.GetResponse() as HttpWebResponse;
     return response;
 }
Example #23
0
 public RequestState()
 {
     BufferRead = new byte[BUFFER_SIZE];
     requestData = new StringBuilder(string.Empty);
     request = null;
     streamResponse = null;
 }
Example #24
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);
		}
Example #25
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);
                }
            }
        }
		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);
			}
		}
        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;
                }
            }
        }
        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;
                }
            }
        }
        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();
                }
            }
        }
Example #30
-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;
        }