本文整理汇总了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;
}
示例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;
}
示例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");
}
}
示例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;
}
示例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 );
}
示例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();
}
}
示例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;
}
示例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";
}
}
示例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);
}
}
示例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());
}
}