当前位置: 首页>>代码示例>>C#>>正文


C# HttpWebRequest.GetResponse方法代码示例

本文整理汇总了C#中System.Net.HttpWebRequest.GetResponse方法的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest.GetResponse方法的具体用法?C# HttpWebRequest.GetResponse怎么用?C# HttpWebRequest.GetResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.HttpWebRequest的用法示例。


在下文中一共展示了HttpWebRequest.GetResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GerarArquivo

        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;
        }
开发者ID:rcarubbi,项目名称:Google.TTS,代码行数:30,代码来源:TTSHelper.cs

示例2: Create

        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;
            }
        }
开发者ID:TlhanGhun,项目名称:digiTweetSnarlEdition,代码行数:29,代码来源:TinyUrlClient.cs

示例3: Download

 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();
         }
     }
 }
开发者ID:bodiroga,项目名称:Avalon,代码行数:35,代码来源:checkForUpdate.cs

示例4: GetHttpWebResp

        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;
        }
开发者ID:ruslanruslanruslan,项目名称:Parser,代码行数:25,代码来源:WebClAlwaysNewProxy.cs

示例5: GetRequestAutoCookie

        public string GetRequestAutoCookie(HttpWebRequest request1, ref string textRef1, ref string textRef2)
        {
            string str3 = "";
            string str2 = "";
            request1.Headers.Add(HttpRequestHeader.Cookie, this._objCookieList.ToString());
            HttpWebResponse response = (HttpWebResponse) request1.GetResponse();
            Stream responseStream = response.GetResponseStream();
            switch (response.ContentEncoding.ToLower())
            {
                case "gzip":
                    responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                    break;

                case "deflate":
                    responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                    break;
            }
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            str3 = reader.ReadToEnd();
            reader.Close();
            textRef1 = response.ResponseUri.ToString();
            textRef2 = response.Headers.Get("Location");
            str2 = response.Headers["Set-Cookie"];
            if (str2 != null && str2 != string.Empty)
            {
                str2 = this.ProcessCookie(str2);
            }
            return str3;
        }
开发者ID:yjtang,项目名称:AutoBws,代码行数:29,代码来源:Core.cs

示例6: doGet

        public string doGet(HttpWebRequest responseDataRequest)
        {
            string result=null;
            try
            {
                var response = (HttpWebResponse)responseDataRequest.GetResponse();//You return this response.
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                    return result;

                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)wex.Response)//You return wex.Response instead
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            return generateErrors(reader, wex);
                        }
                    }
                }
            }

            //refund deserializedProduct = JsonConvert.DeserializeObject<refund>(output);
            return null;
        }
开发者ID:payhub,项目名称:payhubws-public-sdk,代码行数:30,代码来源:WsConnections.cs

示例7: CheckUpdate

        public static void CheckUpdate()
        {
            kIRCVersionChecker.Init();
            Updater = (HttpWebRequest)HttpWebRequest.Create(update_checkerurl);
            Updater_Response = (HttpWebResponse)Updater.GetResponse();

            if (Updater_Response.StatusCode == HttpStatusCode.OK)
            {
                Rocket.Unturned.Logging.Logger.Log("kIRC: Contacting updater...");
                Stream reads = Updater_Response.GetResponseStream();
                byte[] buff = new byte[10];
                reads.Read(buff, 0, 10);
                string ver = Encoding.UTF8.GetString(buff);
                ver = ver.ToLower().Trim(new[] { ' ', '\r', '\n', '\t' }).TrimEnd(new[] { '\0' });

                if (ver == VERSION.ToLower().Trim())
                {
                    Rocket.Unturned.Logging.Logger.Log("kIRC: This plugin is using the latest version!");
                }
                else
                {
                    Rocket.Unturned.Logging.Logger.LogWarning("kIRC Warning: Plugin version mismatch!");
                    Rocket.Unturned.Logging.Logger.LogWarning("Current version: "+VERSION+", Latest version on repository is " + ver + ".");
                }
            }
            else
            {
                Rocket.Unturned.Logging.Logger.LogError("kIRC Error: Failed to contact updater.");
            }
            Updater.Abort();
            Updater = null;
            Updater_Response = null;
            lastchecked = DateTime.Now;
        }
开发者ID:lavery98,项目名称:Rocket_kIRC,代码行数:34,代码来源:kIRCVersionChecker.cs

示例8: GetResponse

        public string GetResponse(HttpWebRequest request)
        {
            ServicePointManager.Expect100Continue = false;

            if (request != null)
                using (var response = request.GetResponse() as HttpWebResponse)
                {

                    try
                    {
                        if (response != null && response.StatusCode != HttpStatusCode.OK)
                        {
                            throw new ApplicationException(
                                string.Format("The request did not compplete successfully and returned status code:{0}",
                                              response.StatusCode));
                        }
                        if (response != null)
                            using (var reader = new StreamReader(response.GetResponseStream()))
                            {
                                return reader.ReadToEnd();
                            }
                    }
                    catch (WebException exception)
                    {
                        return exception.Message;
                    }
                }
            return "The request is null";
        }
开发者ID:avington,项目名称:aviblog,代码行数:29,代码来源:HttpRequestHelper.cs

示例9: GetResponseText

        private static string GetResponseText(HttpWebRequest request)
        {
            string responseText = "";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // PollHaveResponse(request);

                    int contentLength = (int)response.ContentLength;
                    byte[] buffer = new byte[contentLength];
                    Stream stream = response.GetResponseStream();
                    int i = 0;
                    while (i < contentLength)
                    {
                        int readCount = stream.Read(buffer, i, contentLength - i);
                        i += readCount;
                    }

                    char[] responseChars = Encoding.UTF8.GetChars(buffer);
                    responseText = new string(responseChars);
                }
            }
            catch (Exception ex)
            {
                Debug.Print("Exception in GetResponseText: " + ex.Message);
            }

            // PollHaveResponse(request);

            return responseText;
        }
开发者ID:cjdaly,项目名称:napkin,代码行数:33,代码来源:HttpUtil.cs

示例10: GetWebResponse

		/// <summary>
		/// Get a string response from an HttpWebRequest.
		/// </summary>
		/// <param name="Request">A valid HttpWebRequest.</param>
		/// <returns>The string returned from the web request, or an empty string if there was an error.</returns>
		/// <remarks>The response status code needs to be 'OK' for results to be processed. Also, this is designed for simple queries, 
		/// so there is an arbitrary 1024 byte limit to the response size.</remarks>
		static public string GetWebResponse( HttpWebRequest Request )
		{
			string ResponseString = "";

			try
			{
				HttpWebResponse WebResponse = ( HttpWebResponse )Request.GetResponse();
				// Simple size check to prevent exploits
				if( WebResponse.StatusCode == HttpStatusCode.OK && WebResponse.ContentLength < 1024 )
				{
					// Process the response
					Stream ResponseStream = WebResponse.GetResponseStream();
					byte[] RawResponse = new byte[WebResponse.ContentLength];
					ResponseStream.Read( RawResponse, 0, ( int )WebResponse.ContentLength );
					ResponseStream.Close();

					ResponseString = Encoding.UTF8.GetString( RawResponse );
				}
			}
			catch( Exception Ex )
			{
				Debug.WriteLine( "Exception in GetWebResponse: " + Ex.Message );
				ResponseString = "";
			}

			return ResponseString;
		}
开发者ID:xiangyuan,项目名称:Unreal4,代码行数:34,代码来源:SimpleWebRequest.cs

示例11: GetResponseText

		protected virtual string GetResponseText(HttpWebRequest request)
		{
			try
			{
				using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
				{
					string responseText = string.Empty;

					using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
					{
						responseText = reader.ReadToEnd();
					}

					return responseText;
				}
			}
			catch (System.Exception ex)
			{
				string message = string.Format("对地址{0}执行{1}操作错误:{2}",
					request.RequestUri.ToString(),
					request.Method, 
					ex.Message);

				throw new ApplicationException(message, ex);
			}
		}
开发者ID:jerryshi2007,项目名称:AK47Source,代码行数:26,代码来源:WeChatExecutorBase.cs

示例12: Login

        public HttpWebResponse Login(Uri uri, byte[] loginData)
        {
            _request = RequestFactory.GetPostRequest(uri, loginData, Cookies);
            _request.CookieContainer = Cookies;

            return (HttpWebResponse)_request.GetResponse();
        }
开发者ID:brnn8r,项目名称:SadamsCode,代码行数:7,代码来源:LoginRequest.cs

示例13: GetResponseStr

        /// <summary>
        /// Get方法获取Html
        /// </summary>
        /// <param name="request">HttpWebRequest类,包含header</param>
        /// <param name="encoding">网页的编码</param>
        /// <param name="proxy">代理</param>
        /// <param name="timeout">默认设置为2000,可随意</param>
        /// <returns></returns>
        public static string GetResponseStr(HttpWebRequest request, string encoding, WebProxy proxy,int? timeout)
        {
            string html = null;
            try
            {
                if (timeout == null || timeout < 2000)
                {
                    timeout = 2000;
                }

                request.Timeout = timeout.Value;
                request.AllowAutoRedirect = true;
                if (proxy != null)
                    request.Proxy = proxy;
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                if (response.ContentEncoding == "gzip")
                {
                    //StreamReader sr1 = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
                    //是否要解压缩stream?
                    html = GetResponseByZipStream(response);
                    //Console.WriteLine(res);
                }
                else
                {
                    html = sr.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                html = e.Message;
            }

            return html;
        }
开发者ID:heavenlw,项目名称:Awol,代码行数:43,代码来源:WebHelper.cs

示例14: FetchRequest

        public string FetchRequest(HttpWebRequest request)
        {
            try
            {



                string responseText = string.Empty;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            responseText = responseReader.ReadToEnd();
                            return responseText;
                        }
                    }
                }

                return responseText;
            }
            catch (WebException ex)
            {
                var responseStream = ex.Response.GetResponseStream();
                StreamReader responseReader = new StreamReader(responseStream);
                string responseText = responseReader.ReadToEnd();
                throw new MagentoApiException(responseText, ex.Status);
            }
        }
开发者ID:sakthi1985,项目名称:Magent0,代码行数:31,代码来源:ApiClient.cs

示例15: remoteCall

        private static HttpResponse remoteCall( int bufmax, ILog log, HttpWebRequest request )
        {
            HttpWebResponse response;
            try
            {
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                response = e.Response as HttpWebResponse;
            }
            Stream receiveStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader readStream = new StreamReader(receiveStream, encode);
            Char[] read = new Char[bufmax];
            int count = readStream.Read(read, 0, bufmax);
            if (count == bufmax)
                throw new Exception("buf is small ");

            HttpResponse callRespon = new HttpResponse();
            callRespon.body = new String(read, 0, count);
            callRespon.status = response.StatusCode.ToString();
            log.InfoFormat("[GET] status {0} body:{1}", callRespon.status, callRespon.body);
            response.Close();
            readStream.Close();
            return callRespon;
        }
开发者ID:xcodecraft,项目名称:pylon4net,代码行数:27,代码来源:utls.cs


注:本文中的System.Net.HttpWebRequest.GetResponse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。