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


C# HttpResponseMessage.EnsureSuccessStatusCode方法代码示例

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


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

示例1: SendGetRequest

		static public async Task<string> SendGetRequest ( string address )
		{
			var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter ();
			httpFilter.CacheControl.ReadBehavior =
				Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
			httpClient = new HttpClient ( httpFilter );
			response = new HttpResponseMessage ();
			string responseText = "";

			//check address
			Uri resourceUri;
			if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) )
			{
				return "Invalid URI, please re-enter a valid URI";
			}
			if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" )
			{
				return "Only 'http' and 'https' schemes supported. Please re-enter URI";
			}

			//get
			try
			{
				response = await httpClient.GetAsync ( resourceUri );
				response.EnsureSuccessStatusCode ();
				responseText = await response.Content.ReadAsStringAsync ();
			}
			catch ( Exception ex )
			{
				// Need to convert int HResult to hex string
				responseText = "Error = " + ex.HResult.ToString ( "X" ) + "  Message: " + ex.Message;
			}
			httpClient.Dispose ();
			return responseText;
		}
开发者ID:tranchikhang,项目名称:BookShare,代码行数:35,代码来源:RestAPI.cs

示例2: SendPostRequest

		static public async Task<string> SendPostRequest ( object data , string address )
		{
			string json = JsonConvert.SerializeObject ( data );
			//string tokenJson = JsonConvert.SerializeObject ( UserData.token );
			//create dictionary
			var dict = new Dictionary<string , string> ();
			dict["data"] = json;

			httpClient = new HttpClient ();
			response = new HttpResponseMessage ();
			string responseText = "";

			//check address
			Uri resourceUri;
			if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) )
			{
				return "Invalid URI, please re-enter a valid URI";
			}
			if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" )
			{
				return "Only 'http' and 'https' schemes supported. Please re-enter URI";
			}

			//post
			try
			{
				response = await httpClient.PostAsync ( resourceUri , new HttpFormUrlEncodedContent ( dict ) );
				response.EnsureSuccessStatusCode ();
				responseText = await response.Content.ReadAsStringAsync ();
			}
			catch ( Exception ex )
			{
				// Need to convert int HResult to hex string
				responseText = "Error = " + ex.HResult.ToString ( "X" ) + "  Message: " + ex.Message;
			}
			httpClient.Dispose ();
			return responseText;
		}
开发者ID:tranchikhang,项目名称:BookShare,代码行数:38,代码来源:RestAPI.cs

示例3: HttpGet

        public async Task HttpGet(string uri)
        {
            HttpClient httpClient = new HttpClient();

            var headers = httpClient.DefaultRequestHeaders;
            headers.UserAgent.ParseAdd("ie");
            headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            try
            {
                HttpResponseMessage response = new HttpResponseMessage();
                response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute));

                response.EnsureSuccessStatusCode();

                responseString = await response.Content.ReadAsStringAsync();

                var syncBean = JsonConvert.DeserializeObject<SyncBean>(responseString);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("something wrong");
            }
        }
开发者ID:fqncom,项目名称:tomcraporigami,代码行数:23,代码来源:JsonDemo.xaml.cs

示例4: Get

        public static async Task<string> Get(string uri)
        {
            HttpClient httpClient = new HttpClient();
            Myprogress.ProgressIndicator progressIndicator = new Myprogress.ProgressIndicator();
            progressIndicator.Text = "正在加载...";

            progressIndicator.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x23, 0xAC, 0x5B));
         
            progressIndicator.Width = 400;
            progressIndicator.Height = 60;
            progressIndicator.Show();

            var headers = httpClient.DefaultRequestHeaders;
            headers.UserAgent.ParseAdd("ie");
            headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
            try
            {
                HttpResponseMessage response = new HttpResponseMessage();
                response = await httpClient.GetAsync(new Uri(uri,UriKind.Absolute));

                response.EnsureSuccessStatusCode();

                responseString = await response.Content.ReadAsStringAsync();
               
                
               
            }
            catch (Exception ex)
            {
               
                
            }
            progressIndicator.Hide();
            return responseString;

        }
开发者ID:x01673,项目名称:BCMeng_Project,代码行数:36,代码来源:HttpGet.cs

示例5: ProcessResponseAsync

 /// <summary>
 /// Asynchronously processes an HTTP response message, ensuring it was successful and extracting its content.
 /// </summary>
 private static async Task<HttpResponse> ProcessResponseAsync( HttpResponseMessage response, Encoding encoding )
 {
     response.EnsureSuccessStatusCode();
     var buffer = await response.Content.ReadAsBufferAsync();
     byte[] bytes = buffer.ToArray();
     string content = encoding.GetString( bytes, 0, bytes.Length );
     string requestUrl = response.RequestMessage.RequestUri.ToString();
     return new HttpResponse( content, requestUrl );
 }
开发者ID:ValentinMinder,项目名称:pocketcampus,代码行数:12,代码来源:HttpClient.cs

示例6: rafrich

        private async void rafrich()
        {
            if (NetworkInterface.GetIsNetworkAvailable() == true)
            {
                //Do something

                response = new HttpResponseMessage();

                // if 'feedAddress' value changed the new URI must be tested --------------------------------
                // if the new 'feedAddress' doesn't work, 'feedStatus' informs the user about the incorrect input.

                //feedStatus.Text = "Test if URI is valid";

                Uri resourceUri;
                if (!Uri.TryCreate(feedAddress.Trim(), UriKind.Absolute, out resourceUri))
                {
                    //  feedStatus.Text = "Invalid URI, please re-enter a valid URI";
                    return;
                }
                if (resourceUri.Scheme != "http" && resourceUri.Scheme != "https")
                {
                    //feedStatus.Text = "Only 'http' and 'https' schemes supported. Please re-enter URI";
                    return;
                }
                // ---------- end of test---------------------------------------------------------------------

                string responseText;
                //feedStatus.Text = "Waiting for response ...";

                try
                {
                    response = await httpClient.GetAsync(resourceUri);

                    response.EnsureSuccessStatusCode();

                    responseText = await response.Content.ReadAsStringAsync();
                    //statusPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                }
                catch (Exception ex)
                {
                    // Need to convert int HResult to hex string
                    //  feedStatus.Text = "Error = " + ex.HResult.ToString("X") +  "  Message: " + ex.Message;
                    responseText = ex+"";
                }
                //  feedStatus.Text = response.StatusCode + " " + response.ReasonPhrase;

                // now 'responseText' contains the feed as a verified text.
                // next 'responseText' is converted as the rssItems class model definition to be displayed as a list

                List<ItemsRSS> lstData = new List<ItemsRSS>();

                XElement _xml = XElement.Parse(responseText);
                foreach (XElement value in _xml.Elements("channel").Elements("item"))
                {
                    ItemsRSS _item = new ItemsRSS();

                    _item.Title = value.Element("title").Value;

                    _item.Description = value.Element("description").Value;

                    _item.Link = value.Element("link").Value;

                    _item.Category = value.Element("category").Value;

                    _item.Image = value.Element("enclosure").Attribute("url").Value;

                    lstData.Add(_item);
                }

                // lstRSS is bound to the lstData: the final result of the RSS parsing
                lstRSS.DataContext = lstData;

            }
            else
            {
                MessageDialog msg = new MessageDialog("No Network !!", "Network Erreur !");
                await msg.ShowAsync();
            }
        }
开发者ID:Karouinour,项目名称:Drugs-Reminder-Windows,代码行数:80,代码来源:MainPage.xaml.cs

示例7: GetRouteDirections

        public async static Task<XDocument> GetRouteDirections(string route)
        {
            var client = new HttpClient();
            var response = new HttpResponseMessage();
            var xmlDoc = new XDocument();

            var url = baseUrls["routeConfig"] + route;

            //Make sure to pull from network not cache everytime predictions are refreshed 
            client.DefaultRequestHeaders.IfModifiedSince = DateTime.Now;
            try
            {
                response = await client.GetAsync(new Uri(url));
                response.EnsureSuccessStatusCode();
                xmlDoc = await Task.Run(async () => XDocument.Parse(await response.Content.ReadAsStringAsync()));
            }
            catch (Exception)
            {
                await ErrorHandler.NetworkError("Error getting route information. Check your network connection and try again.");
                throw;
            }

            response.Dispose();
            client.Dispose();

            return xmlDoc;
        }
开发者ID:nexDevelopment,项目名称:nexMUNI,代码行数:27,代码来源:WebHelper.cs

示例8: GetFromJwch

 public static async Task<string> GetFromJwch(string method,string purpose,HttpFormUrlEncodedContent content,bool tokenRequire = false)
 {
     string uri;
     switch (purpose)
     {
         case "Login":
             uri = Login;
             break;
         case "getTimetable":
             uri = getTimetable;
             break;
         case "getScore":
             uri = getScore;
             break;
         case "getExamRoom":
             uri = getExamRoom;
             break;
         case "getBookSearchResult":
             uri = getBookSearchResult;
             break;
         case "getJwchNotice":
             uri = getJwchNotice;
             break;
         case "getGradePoint":
             uri = getGradePoint;
             break;
         case "getEmptyRoom":
             uri = getEmptyRoom;
             break;
         case "getCurrentWeek":
             uri = getCurrentWeek;
             break;
         default:
             uri = "";
             break;
     }
     HttpResponseMessage httpResponse = new HttpResponseMessage();
     string httpResponseBody = "";
     try
     {
         if (method == "post")
         {
             httpResponse = await httpClient.PostAsync(new Uri(uri), content);
         }
         else
         {
             string con = await content.ReadAsStringAsync();
             uri = uri + "?" + con;
             httpResponse = await httpClient.GetAsync(new Uri(uri));
         }
         httpResponse.EnsureSuccessStatusCode();
         httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
         //Check if the return data is correct
         try
         {
             if (tokenRequire)
             {
                 CheckJwch c = JsonConvert.DeserializeObject<CheckJwch>(httpResponseBody);
                 if (c.errMsg != "" && c.errMsg != null)
                 {
                     await ReLogin();
                     return "relogin";
                 }
             }
             return httpResponseBody;
         }
         catch
         {
             return httpResponseBody;
         }
     }
     catch
     {
         NotifyPopup notifyPopup = new NotifyPopup("网络错误");
         notifyPopup.Show();
         return "error";
     }
 }
开发者ID:C2CCC,项目名称:Fzuhelper,代码行数:78,代码来源:HttpRequest.cs

示例9: EnsureSuccessStatusCode_AddContentToMessage_ContentIsDisposed

        public void EnsureSuccessStatusCode_AddContentToMessage_ContentIsDisposed()
        {
            using (var response404 = new HttpResponseMessage(HttpStatusCode.NotFound))
            {
                response404.Content = new MockContent();
                Assert.Throws<HttpRequestException>(() => response404.EnsureSuccessStatusCode());
                Assert.True((response404.Content as MockContent).IsDisposed);
            }

            using (var response200 = new HttpResponseMessage(HttpStatusCode.OK))
            {
                response200.Content = new MockContent();
                response200.EnsureSuccessStatusCode(); // No exception.
                Assert.False((response200.Content as MockContent).IsDisposed);
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:16,代码来源:HttpResponseMessageTest.cs

示例10: EnsureSuccessStatusCode_VariousStatusCodes_ThrowIfNot2xx

        public void EnsureSuccessStatusCode_VariousStatusCodes_ThrowIfNot2xx()
        {
            using (var m = new HttpResponseMessage(HttpStatusCode.MultipleChoices))
            {
                Assert.Throws<HttpRequestException>(() => m.EnsureSuccessStatusCode());
            }

            using (var m = new HttpResponseMessage(HttpStatusCode.BadGateway))
            {
                Assert.Throws<HttpRequestException>(() => m.EnsureSuccessStatusCode());
            }

            using (var response = new HttpResponseMessage(HttpStatusCode.OK))
            {
                Assert.Same(response, response.EnsureSuccessStatusCode());
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:17,代码来源:HttpResponseMessageTest.cs


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