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


C# HttpResponseMessage.EnsureSuccessStatusCode方法代码示例

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


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

示例1: PostRequest

        private async Task<string> PostRequest(string URL)
        {
            System.Diagnostics.Debug.WriteLine("URL:" + URL);

            Uri requestUri = new Uri(URL);

            //Add a user-agent header to the GET request. 
            var headers = httpClient.DefaultRequestHeaders;

            HttpResponseMessage httpResponse = new HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.PostAsync(requestUri, null);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                System.Diagnostics.Debug.WriteLine("Response:" + httpResponseBody);
                return httpResponseBody;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
开发者ID:lamarios,项目名称:Pydio-UWP,代码行数:28,代码来源:API.cs

示例2: CreateResult

 public override Result CreateResult(HttpResponseMessage responseMessage, IContext context)
 {
     responseMessage.EnsureSuccessStatusCode();
     
     ProcessEventsUntilStopped(responseMessage, context);
     
     return null;
 }
开发者ID:snargledorf,项目名称:Sharpbase,代码行数:8,代码来源:EventListenerRequest.cs

示例3: getInfo

 public static async Task<string> getInfo(string URL)
 {
     HttpClient client = new HttpClient();
     HttpResponseMessage response = new HttpResponseMessage();
     response = await client.GetAsync(URL);
     response.EnsureSuccessStatusCode();
     Response = await response.Content.ReadAsStringAsync();
     return Response;
 }
开发者ID:BankaSgushenki,项目名称:lostfilm.tv-app-win8,代码行数:9,代码来源:GetHtml.cs

示例4: Initialize

        /// <summary>
        /// Initializes connection to Hue bridge
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        public void Initialize(string url, string username)
        {
            if (url.LastIndexOf('/') == url.Length - 1) { url = url.Substring(0, url.Length - 1); }

            //connect to bridge using IP address from config file

            //assume connected app and username from config file

            //ping bridge to ensure connectivity

            _bridgeApiBase = new Uri(string.Format("{0}/api/{1}", url, username));

            try
            {
                HttpResponseMessage response = new HttpResponseMessage();

                // Create a Http Call for Access Token
                HttpClient client = new HttpClient();
                client.BaseAddress = _bridgeApiBase;

                client.GetAsync(_bridgeApiBase + "/lights").ContinueWith(
                    (getTask) =>
                    {
                        if (getTask.IsCanceled) { return; }
                        if (getTask.IsFaulted) { throw getTask.Exception; }
                        response = getTask.Result;

                        response.EnsureSuccessStatusCode();
                    }).Wait();

                string result = response.Content.ReadAsStringAsync().Result.ToString();

                this.Lights = new Dictionary<string, Light>();

                JToken token = JToken.Parse(result);
                if (token.Type == JTokenType.Object)
                {
                    var lightsJSON = (JObject)token;
                    foreach (var prop in lightsJSON.Properties())
                    {
                        Light newLight = JsonConvert.DeserializeObject<Light>(prop.Value.ToString());
                        newLight.Id = prop.Name.ToString();
                        this.Lights.Add(newLight.Name.ToLower(), newLight);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error initializing HueManager.  Check inner exception for details.", ex);
            }
        }
开发者ID:smithderekm,项目名称:rducc-cortana,代码行数:56,代码来源:HueManager.cs

示例5: EnsureSuccessStatusCode

        public void EnsureSuccessStatusCode()
        {
            HttpResponseMessage message = new HttpResponseMessage ();
            Assert.AreSame (message, message.EnsureSuccessStatusCode (), "#1");

            message = new HttpResponseMessage (HttpStatusCode.BadRequest);
            message.ReasonPhrase = "test reason";
            try {
                message.EnsureSuccessStatusCode ();
                Assert.Fail ("#2");
            } catch (HttpRequestException e) {
                Assert.IsTrue (e.Message.Contains ("400 (test reason)"), "#3");
            }
        }
开发者ID:RainsSoft,项目名称:dotnet-httpclient35,代码行数:14,代码来源:HttpResponseMessageTest.cs

示例6: EnsureSuccessOrThrow

 private async Task<bool> EnsureSuccessOrThrow(HttpResponseMessage resp)
 {
     if (resp.IsSuccessStatusCode)
     {
         return true;
     }
     if (resp.StatusCode == HttpStatusCode.BadRequest || resp.StatusCode == HttpStatusCode.InternalServerError)
     {
         var msg = await resp.Content.ReadAsStringAsync();
         throw new SelfossServerException(msg, null);
     }
     resp.EnsureSuccessStatusCode();
     return true;
 }
开发者ID:gleroi,项目名称:selfnet,代码行数:14,代码来源:HttpGateway.cs

示例7: Get

		public async Task<string> Get(string baseURI, string uri, bool authenticate = true)
		{
			await CheckAPIResponsiveness();
			if (authenticate)
			{
				await AddAuthenticationHeader();
			}

			HttpResponseMessage response = new HttpResponseMessage();

			Client.BaseAddress = new Uri(baseURI);
			response = await Client.GetAsync(uri);
			response.EnsureSuccessStatusCode();

			TokenManager.LastRefresh = DateTime.UtcNow;
			return await response.Content.ReadAsStringAsync();
		}
开发者ID:MobileFit,项目名称:CoachV2,代码行数:17,代码来源:MemberProfileService.cs

示例8: WebPageToString

        private async Task<string> WebPageToString(string link) {
            HttpClient httpClient = new HttpClient();
            Uri requestUri = new Uri(link);
            HttpResponseMessage httpResponse = new HttpResponseMessage();
            string httpResponseBody = string.Empty;

            try {
                httpResponse = await httpClient.GetAsync(requestUri);
                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex) {
                httpResponseBody = string.Format("Error: {0}  Message: ", ex.HResult.ToString("X"), ex.Message);
            }

            return httpResponseBody;
        }
开发者ID:ronlemire2,项目名称:UWP-Apps,代码行数:17,代码来源:ComicsService.cs

示例9: SelectUserForEvent

		/**
		 * Concatenate a Uri with the given parameters.
		 * If uri invokation was succesfull a list with all users for the given eventId and state will be created,
		 * which will be stored in the variable listUser.
		 **/
		public async Task<List<MySqlUser>> SelectUserForEvent(string host, int idEvent, string state) {
			HttpResponseMessage response = new HttpResponseMessage();
			Uri uri = new Uri(host + "php/requestUserForEvent.php?idEvent=" + idEvent + "&state="  + state);

			List<MySqlUser> listUser = null;
			string responseText;
			try {
				response = await client.GetAsync(uri).ConfigureAwait(continueOnCapturedContext:false);
				response.EnsureSuccessStatusCode();
				responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext:false);

				listUser = createUserFromResponse(responseText);
			} catch(Exception e) {
				Console.WriteLine("Error while selecting data from MySQL: " + e.Message);
			}
			return listUser;
		}
开发者ID:MxPtrs,项目名称:Karlsfeld-Volleyball-App,代码行数:22,代码来源:DB_SelectUser.cs

示例10: PostAsync

 public static void PostAsync(string _URL, object _DATA, TConnector.ConnectorOnEventDelegate _onresponse = null, TConnector.ConnectorOnEventDelegate _onerror = null)
 {
     var client = new HttpClient();
     byte[] bytes;
     bytes = System.Text.Encoding.ASCII.GetBytes(_DATA.ToString());
     HttpContent content = new ByteArrayContent(bytes);
     client.PostAsync(_URL, content).ContinueWith(
         (postTask) =>
         {
             object retval;
             HttpResponseMessage msg = new HttpResponseMessage();
             try
             {
                 msg = postTask.Result;
                 msg.EnsureSuccessStatusCode();
             }
             catch (Exception ex)
             {
                 if (_onerror != null)
                     _onerror(ex);
                 return;
             }
             Task<Stream> objResponseStreamTask = msg.Content.ReadAsStreamAsync();
             Stream objResponseStream = objResponseStreamTask.Result;
             XmlDocument xmldoc = new XmlDocument();
             try
             {
                 XmlTextReader objXMLReader = new XmlTextReader(objResponseStream);
                 xmldoc.Load(objXMLReader);
                 objXMLReader.Close();
                 retval = xmldoc;
             }
             catch (Exception)
             {
                 objResponseStream.Position = 0;
                 StreamReader sr = new StreamReader(objResponseStream);
                 retval = sr.ReadToEnd();
             }
             if (_onresponse != null)
                 _onresponse(retval);
         });
 }
开发者ID:artemablitsov,项目名称:PPFSendII,代码行数:42,代码来源:THTTP.cs

示例11: InsertUser

		/**
		 * Inserts a user with the given parameters and userId = currentHighestId + 1.
		 * You can check if the insert was succesful in the succes variable.
		 **/
		public async Task<bool> InsertUser(string host, string name, string role, string password, int number, string position) {
			HttpResponseMessage response = new HttpResponseMessage();
			Uri uri = new Uri(host + "php/insertUser.php" + "?name=" + name + "&role=" + role + "&password=" + password + "&number=" + number + "&position=" + position);

			string responseText;
			try {
				response = await client.GetAsync(uri);
				response.EnsureSuccessStatusCode();
				responseText = await response.Content.ReadAsStringAsync();

				if(dbCommunicator.wasSuccesful(responseText)) {
					return true;
				}

				if(debug) {
					Console.WriteLine("Insert response: " + responseText);
				}
			} catch(Exception e) {
				Console.WriteLine("Error while selecting data from MySQL: " + e.Message);
				return false;
			}
			return false;
		}
开发者ID:Tucaen,项目名称:Karlsfeld-Volleyball-App,代码行数:27,代码来源:DB_Insert.cs

示例12: validateLogin

		public async Task<MySqlUser> validateLogin(string host, string username, string password) {
			HttpResponseMessage response = new HttpResponseMessage();
			Uri uri = new Uri(host + "php/validateLogin.php?username=" + username + "&password="  + password);
			if(debug) 
				Console.WriteLine("Login uri: " + uri);

			MySqlUser user = null;
			string responseText;
			try {
				response = await client.GetAsync(uri).ConfigureAwait(continueOnCapturedContext:false);
				Console.WriteLine("selectuser - response statuscode = " + response.StatusCode);
				response.EnsureSuccessStatusCode();
				responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext:false);
				user  = createUserFromResponse(responseText)[0];

				if(debug) 
					Console.WriteLine("Login response: " + responseText);
				
			} catch(Exception e) {
				Console.WriteLine("Error while loging in: " + e.Message + " Source: "  + e.InnerException + " | " + e.StackTrace);
			}
			return user;
		}
开发者ID:MxPtrs,项目名称:Karlsfeld-Volleyball-App,代码行数:23,代码来源:DB_SelectUser.cs

示例13: DeleteUser

		/**
		 * Delets a user with the given userId.
		 * You can check if the insert was succesful in the succes variable.
		 **/
		public async Task<bool> DeleteUser(string host, int idUser) {
			HttpResponseMessage response = new HttpResponseMessage();
			Uri uri = new Uri(host + "php/deleteUser.php" + "?idUser=" + idUser);

			string responseText;
			try {
				response = await client.GetAsync(uri);
				response.EnsureSuccessStatusCode();
				responseText = await response.Content.ReadAsStringAsync();

				if(dbCommunicator.wasSuccesful(responseText)) {
					return true;
				}

				if(debug) {
					Console.WriteLine("Delete response: " + responseText);
				}
			} catch(Exception e) {
				Console.WriteLine("Error while selecting data from MySQL: " + e.Message);
				return false;
			}
			return false;
		}
开发者ID:Tucaen,项目名称:Karlsfeld-Volleyball-App,代码行数:27,代码来源:DB_Delete.cs

示例14: EnsureSuccessStatusCode

 void EnsureSuccessStatusCode(HttpResponseMessage m)
 {
     if (m.StatusCode == HttpStatusCode.Forbidden)
     {
         throw new HttpForbiddenException();
     }
     if (m.StatusCode == HttpStatusCode.GatewayTimeout)
     {
         throw new HttpConnectionException();
     }
     if (m.StatusCode == HttpStatusCode.NotFound)
     {
         throw new HttpNotFoundException();
     }
     m.EnsureSuccessStatusCode();
 }
开发者ID:killbug2004,项目名称:WSProf,代码行数:16,代码来源:RestClient.cs

示例15: PrintResponse

        public static void PrintResponse(HttpResponseMessage response)
        {
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Response:");
            Console.WriteLine(response);

            if (response.Content != null)
            {
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:11,代码来源:ODataAttributeRoutingSample.cs


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