本文整理汇总了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;
}
}
示例2: CreateResult
public override Result CreateResult(HttpResponseMessage responseMessage, IContext context)
{
responseMessage.EnsureSuccessStatusCode();
ProcessEventsUntilStopped(responseMessage, context);
return null;
}
示例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;
}
示例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);
}
}
示例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");
}
}
示例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;
}
示例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();
}
示例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;
}
示例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;
}
示例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);
});
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
示例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);
}
}