• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# WebRequest类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中WebRequest的典型用法代码示例。如果您正苦于以下问题:C# WebRequest类的具体用法?C# WebRequest怎么用?C# WebRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



WebRequest类属于命名空间,在下文中一共展示了WebRequest类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: process

 public void process(WebRequest request)
 {
     Sentence sentence = "这是一个回答";
     var tags = new List<Keyword> {"测试"};
     service.answer(sentence, tags);
     request.Output.Display(new View("Install.cshtml"));
 }
开发者ID:SkightTeam,项目名称:eLiteWeb,代码行数:7,代码来源:Install.cs


示例2: BeginProcessRequest

    public void BeginProcessRequest(Site site)
    {
        string sql = "";
        int iResult = 0;
        this.Site = site;

        oDataIO = new DataIO();
        SqlConnection Conn = new SqlConnection();
        Conn = oDataIO.GetDBConnection("ProfilesDB");
        sqlCmd = new SqlCommand();
        sqlCmd.Connection = Conn;

        site.IsDone = false;
        _request = WebRequest.Create(site.URL);

        // Enter log record
        sql = "insert into FSLogOutgoing(FSID,SiteID,Details,SentDate,QueryString) "
             + " values ('" + site.FSID.ToString() + "'," + site.SiteID.ToString() + ",0,GetDate()," + cs(site.SearchPhrase) + ")";
        sqlCmd.CommandText = sql;
        sqlCmd.CommandType = System.Data.CommandType.Text;
        iResult = sqlCmd.ExecuteNonQuery();

        if (sqlCmd.Connection.State == System.Data.ConnectionState.Open)
            sqlCmd.Connection.Close();

        _request.BeginGetResponse(new AsyncCallback(EndProcessRequest), site);
    }
开发者ID:anirvan,项目名称:ProfilesRNSBeta-OpenSocial,代码行数:27,代码来源:DirectService.aspx.cs


示例3: Run

        // Wrapper for Run which takes care of CloudFlare challenges, calls RunCurl
        override protected async Task<WebClientByteResult> Run(WebRequest request)
        {
            WebClientByteResult result = await RunCurl(request);

            // check if we've received a CloudFlare challenge
            string[] server;
            if (result.Status == HttpStatusCode.ServiceUnavailable && result.Headers.TryGetValue("server", out server) && server[0] == "cloudflare-nginx")
            {
                logger.Info("UnixLibCurlWebClient: Received a new CloudFlare challenge");

                // solve the challenge
                string pageContent = Encoding.UTF8.GetString(result.Content);
                Uri uri = new Uri(request.Url);
                string clearanceUri = CloudFlareChallengeSolverSolve(pageContent, uri);
                logger.Info(string.Format("UnixLibCurlWebClient: CloudFlare clearanceUri: {0}", clearanceUri));

                // wait...
                await Task.Delay(5000);

                // request clearanceUri to get cf_clearance cookie
                var response = await CurlHelper.GetAsync(clearanceUri, request.Cookies, request.Referer);
                logger.Info(string.Format("UnixLibCurlWebClient: received CloudFlare clearance cookie: {0}", response.Cookies));

                // add new cf_clearance cookies to the original request
                request.Cookies = response.Cookies + request.Cookies;

                // re-run the original request with updated cf_clearance cookie
                result = await RunCurl(request);

                // add cf_clearance cookie to the final result so we update the config for the next request
                result.Cookies = response.Cookies + " " + result.Cookies;
            }
            return result;
        }
开发者ID:Jackett,项目名称:Jackett,代码行数:35,代码来源:UnixLibCurlWebClient.cs


示例4: GetString

 public async Task<WebClientStringResult> GetString(WebRequest request)
 {
     logger.Debug(string.Format("UnixLibCurlWebClient:GetString(Url:{0})", request.Url));
     var result = await Run(request);
     logger.Debug(string.Format("UnixLibCurlWebClient:GetString Returning {0} => {1}", result.Status, (result.Content == null ? "<NULL>" : Encoding.UTF8.GetString(result.Content))));
     return Mapper.Map<WebClientStringResult>(result);
 }
开发者ID:CatmanIX,项目名称:Shades,代码行数:7,代码来源:UnixLibCurlWebClient.cs


示例5: Request

        // Make an Api request
        public static string Request(string action, Dictionary<string, string> parameters = null)
        {
            // Build the url
            string destination = puushHome + "api/" + action;

            // Create request
            WebRequest req = new WebRequest();

            // Set the desination
            req.Destination(destination);

            // Create post content
            HttpContent content = new FormUrlEncodedContent(parameters);

            // Call the get request
            req.Post(content);

            // Wait for Response to be populated
            while (req.Response == null)
            {
            }

            // Return the response
            return req.Response;
        }
开发者ID:flashwave,项目名称:puush-wp,代码行数:26,代码来源:Api.cs


示例6: getResponse

 /// <summary>
 /// Gets the response and modify the headers.
 /// </summary>
 /// <returns>The response.</returns>
 /// <param name="request">Request.</param>
 public override WebResponse getResponse(WebRequest request)
 {
     WebResponse response = base.getResponse(request);
     //
     // Only if Url matches
     //
     if (request.getUrl().toExternalForm().Contains("com")) {
         string content = response.getContentAsString("UTF-8");
         java.util.ArrayList newheaders = new java.util.ArrayList();
         java.util.List headers = response.getResponseHeaders();
         java.util.Iterator it = headers.iterator();
         //
         // Remove the 'Access-Control-Allow-Origin' header
         //
         while (it.hasNext()) {
             com.gargoylesoftware.htmlunit.util.NameValuePair o = (com.gargoylesoftware.htmlunit.util.NameValuePair)it.next();
             if (o.getName().Equals("Access-Control-Allow-Origin")) {
                 string value = response.getResponseHeaderValue("Access-Control-Allow-Origin");
                 Console.WriteLine("Found header 'Access-Control-Allow-Origin' = \"{0}\" and stripping it from new headers for response", value);
                 continue; //headers.remove(o);
             }
             newheaders.add(o);
         }
         byte[] utf = System.Text.Encoding.UTF8.GetBytes(content);
         WebResponseData data = new WebResponseData(utf,
             response.getStatusCode(), response.getStatusMessage(), newheaders);
         response = new WebResponse(data, request, response.getLoadTime());
         return response;
     }
     return response;
 }
开发者ID:buonan,项目名称:SeleniumTests,代码行数:36,代码来源:WebConnectionWrapper.cs


示例7: InternalAuthenticate

		static Authorization InternalAuthenticate (WebRequest webRequest, ICredentials credentials)
		{
			HttpWebRequest request = webRequest as HttpWebRequest;
			if (request == null || credentials == null)
				return null;

			NetworkCredential cred = credentials.GetCredential (request.AuthUri, "basic");
			if (cred == null)
				return null;

			string userName = cred.UserName;
			if (userName == null || userName == "")
				return null;

			string password = cred.Password;
			string domain = cred.Domain;
			byte [] bytes;

			// If domain is set, MS sends "domain\user:password". 
			if (string.IsNullOrWhiteSpace(domain))
				bytes = GetBytes (userName + ":" + password);
			else
				bytes = GetBytes (domain + "\\" + userName + ":" + password);

			string auth = "Basic " + Convert.ToBase64String (bytes);
			return new Authorization (auth);
		}
开发者ID:henricj,项目名称:SM.Mono.Net,代码行数:27,代码来源:BasicClient.cs


示例8: SendRequest

        public void SendRequest(WebRequest request)
        {
            ResponseUri = request.RequestUri;

            request.Header = request.Method + " " + ResponseUri.PathAndQuery + " HTTP/1.0\r\n" + request.Headers;
            Socket.Send(Encoding.ASCII.GetBytes(request.Header));
        }
开发者ID:khoaakt,项目名称:uitthesis,代码行数:7,代码来源:WebResponse.cs


示例9: GetBytes

 public async Task<WebClientByteResult> GetBytes(WebRequest request)
 {
     logger.Debug(string.Format("UnixLibCurlWebClient:GetBytes(Url:{0})", request.Url));
     var result = await Run(request);
     logger.Debug(string.Format("UnixLibCurlWebClient:GetBytes Returning {0} => {1} bytes", result.Status, (result.Content == null ? "<NULL>" : result.Content.Length.ToString())));
     return result;
 }
开发者ID:CatmanIX,项目名称:Shades,代码行数:7,代码来源:UnixLibCurlWebClient.cs


示例10: SendPostRequest

        /// <summary>
        /// Send a simple Post request
        /// </summary>
        /// <param name="ip">IP of client</param>
        /// <returns></returns>
        /// <remarks>Used port 80</remarks>
        public static string SendPostRequest(string ip)
        {
            WebRequest webRequest = new WebRequest(ip, "POST");
            var response = webRequest.GetResponse();

            return response;
        }
开发者ID:Richard210363,项目名称:Haptic-Theatre-Vibings-Control,代码行数:13,代码来源:HTTPManager.cs


示例11: QueueIfOnline

    public void QueueIfOnline(Action task)
    {
        lock (tasksIfOnline)
        {
            tasksIfOnline.Enqueue(task);
        }

        if(!this.checking)
        {
            // Quickly check this setting which is not accurate
            if(Application.internetReachability != NetworkReachability.NotReachable)
            {
                // Go on and make a real request to see if we can access the internet
                this.request = WebRequest.Create("http://www.google.com/");
                this.request.Method = "GET";
                this.request.Proxy = null;
                this.request.BeginGetResponse(new AsyncCallback(AsyncWebRequest), null);

                this.checking = true;
            }
            else
            {
                Debug.Log("No internet, so clearing tasks");
                this.RespondToInternetCheck(false);

                this.checking = false;
            }
        }
    }
开发者ID:SuperStarPL,项目名称:Radius,代码行数:29,代码来源:InternetTapQueue.cs


示例12: can_process

 public bool can_process(WebRequest request)
 {
     var request_and_query = request.Input.RequestPath.Split('?');
     var request_list = request_and_query[0].Split('/');
     var request_last = request_list[request_list.Length-1];
     return command_name + suffix==request_last;
 }
开发者ID:SkightTeam,项目名称:eLiteWeb,代码行数:7,代码来源:NameConventionFilter.cs


示例13: reqFinished

 //private ->public
 public virtual void reqFinished(WebRequest req)
 {
     if (req.www.error != null) {
         Debug.LogError (" req error:" + req.dumpRequest());
     } else {
         Hashtable t = MiniJsonExtensions.hashtableFromJson (req.www.text);
         if (t == null) {
             Debug.LogError ("http call return empty");
             this.onError("Null HashTable","Null HashTable",null);
             return;
         }
         // {"protocolVersion":1,"serverTime":"2013-11-29 15:24:42,727","serverTimestamp":1385709882,"data":[{"requestId":null,"messages":{},"result":"aWeha_JMFgzaF5zWMR3tnObOtLZNPR4rO70DNdfWPvc.eyJ1c2VySWQiOiIyMCIsImV4cGlyZXMiOiIxMzg1NzA5ODgyIn0","status":0}]}
         ArrayList datas = t["data"] as ArrayList;
         if(datas == null || datas.Count != 1){
             Debug.LogError ("http call return no data");
             this.onError("Null Data","Null Data",null);
             return;
         }
         Hashtable data = datas[0] as Hashtable;
         string status = "" + data ["status"];
         Hashtable result = data["result"] as Hashtable;
         if(result == null && data["result"] is string){
             result = data;
         }
         if(result!=null)Debug.Log (Utils.dumpHashTable (result));
         if (status != "0" ) {
             Debug.LogError ("status=" + status );
             onError (status, status, result);
         } else{
             onComplete(result);
         }
     }
 }
开发者ID:rogeryuan99,项目名称:Hello,代码行数:34,代码来源:Command.cs


示例14: ProcessRequest

        //TODO simple JSON writer
        //struct Info
        //{
        //    public string Provider { get; set; }
        //}
        public override void ProcessRequest(WebRequest request)
        {
            //We don't need a list here, but I rather get away from the lock quicker.
            var dependencies = new System.Collections.Generic.List<ResourceDependancy>();
            WebServer.ForEachPage((page) =>
            {
                var dpd = page.GetDependencies();
                if (dpd != null)
                {
                    dependencies.AddRange(dpd);
                }
            });

            //Since we are using a list we can make it a bit easier
            request.Writer.Buffer(dependencies.Count);

            foreach (var item in dependencies)
            {
                request.Writer.Buffer((byte)item.Type);
                request.Writer.Buffer(item.Url);
            }

            dependencies.Clear();
            dependencies = null;

            request.WriteOut("application/octet-stream");
        }
开发者ID:DeathCradle,项目名称:Terraria-s-Dedicated-Server-Mod,代码行数:32,代码来源:WebModules.cs


示例15: Session

        public WebRequest Session()
        {
            WebRequest wr = new WebRequest();

            Scaffold scaffold = new Scaffold(R, "/app/debug/debug.html", "", new string[] { "body" });
            string jsonVs = R.Util.Str.GetString(R.Session["viewstates"]);
            string jsonUser = R.Util.Serializer.WriteObjectAsString(R.User);
            ViewStates vss = (ViewStates)R.Util.Serializer.ReadObject(jsonVs, Type.GetType("Rennder.ViewStates"));
            List<string> body = new List<string>();
            double totalLen = R.Session["viewstates"].Length;
            double len = 0;

            body.Add("<h1>User (" + (jsonUser.Length * 2) + " bytes)</h1>" + jsonUser);
            body.Add("<h1>Viewstates (" + totalLen.ToString("N0") + " bytes)</h1>" + jsonVs);

            foreach(structViewStateInfo item in vss.Views)
            {
                ViewState vssItem = (ViewState)R.Util.Serializer.ReadObject(R.Util.Str.GetString(R.Session["viewstate-" + item.id]), Type.GetType("Rennder.ViewState"));
                len = R.Session["viewstate-" + item.id].Length;
                totalLen += len;
                body.Add("<h1>Viewstate \"" + item.id + "\" (" + len.ToString("N0") + " bytes)</h1>" + R.Util.Serializer.WriteObjectAsString(vssItem));

            }

            body.Add("<h1>Total Memory Used: " + totalLen.ToString("N0") + " bytes");

            scaffold.Data["body"] = ("<pre>" + string.Join("</pre></div><div><pre>", body.ToArray()).Replace("\\\"", "\"").Replace("\\n", "").Replace("},", "},\n").Replace("],", "],\n") + "</pre>");

            //finally, scaffold debug HTML
            wr.html = scaffold.Render();
            return wr;
        }
开发者ID:nhtera,项目名称:Home,代码行数:32,代码来源:Debug.cs


示例16: ProcessRequest

        public override void ProcessRequest(WebRequest request)
        {
            System.IO.FileInfo info = null;
            if (!String.IsNullOrEmpty(Terraria.Main.worldPathName))
            {
                info = new System.IO.FileInfo(Terraria.Main.worldPathName);
            }

            request.Writer.Buffer(Terraria.Main.worldName ?? String.Empty);
            request.Writer.Buffer(Terraria.Main.maxTilesX);
            request.Writer.Buffer(Terraria.Main.maxTilesY);

            if (info != null && info.Exists)
            {
                request.Writer.Buffer(info.Length);
            }
            else
            {
                request.Writer.Buffer(0L);
            }

            request.Writer.Buffer(Heartbeat.Enabled);
            request.Writer.Buffer(Heartbeat.ServerName);
            request.Writer.Buffer(Heartbeat.ServerDescription);
            request.Writer.Buffer(Heartbeat.ServerDomain);
            request.Writer.Buffer(Heartbeat.PublishToList);

            request.WriteOut();
        }
开发者ID:DeathCradle,项目名称:Terraria-s-Dedicated-Server-Mod,代码行数:29,代码来源:Info.cs


示例17: FixedUpdate

    void FixedUpdate()
    {
        Debug.Log("sending HTTP request! to:");
            Debug.Log(url);
            mycoord = WebRequest.Create(url);
            Stream objStream;
            objStream = mycoord.GetResponse().GetResponseStream();
        StreamReader objReader = new StreamReader(objStream);

            sLine = objReader.ReadLine ();
            Debug.Log("Got response!");
            if(sLine.Length > 4) {
                coordinates = sLine;
            }

        Debug.Log(coordinates);

        int x = System.Convert.ToInt32 (coordinates [1]);
        int y = System.Convert.ToInt32 (coordinates [3]);
        float newX = 0 + (x * 2);
        newX -= 96; //for some reason unity jumps my cardboard main to 96,-96
        float newZ = 0 - (y * 2);
        newZ += 96;
        transform.position = new Vector3(newX, 1.5f,newZ);
    }
开发者ID:nieknooijens,项目名称:VRFloorTrackingResearch,代码行数:25,代码来源:playercontrollerWorksbutwithLag.cs


示例18: CreateFrom

        public WebRequest CreateFrom(HttpContext context)
        {
            var webrequest = new WebRequest();
            webrequest.RequestedUrl = context.Request.Url.ToString();
            webrequest.QueryArguments = context.Request.QueryString;

            return webrequest;
        }
开发者ID:roberth3,项目名称:FrontControllerLab1,代码行数:8,代码来源:WebRequestFactory.cs


示例19: Connect

        public void Connect(WebRequest request)
        {
            ResponseUri = request.RequestUri;

            Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEP = new IPEndPoint(Dns.GetHostEntry(ResponseUri.Host).AddressList[0], ResponseUri.Port);
            Socket.Connect(remoteEP);
        }
开发者ID:khoaakt,项目名称:uitthesis,代码行数:8,代码来源:WebResponse.cs


示例20: CheckValidationResult

 public bool CheckValidationResult(
       ServicePoint srvPoint
     , X509Certificate certificate
     , WebRequest request
     , int certificateProblem)
 {
     //Return True to force the certificate to be accepted.
     return true;
 }
开发者ID:SaltPayments,项目名称:salt-payment-client-dotnet,代码行数:9,代码来源:StorageGatewayTest.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# WebSocket类代码示例发布时间:2022-05-24
下一篇:
C# WebParameterCollection类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap