我正在开发一个 xamarin 表单应用程序,我使用我们的 api。我需要检查“HttpResponseMessage”。我可以在“get”方法中检查这一点,但在“post”方法中无法弄清楚。 我如何在 post 方法中检查此响应?
这是我的代码:
try
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
response = await client.GetAsync(result);
if (response.IsSuccessStatusCode == true)
{
//Convert Json
return JsonConvert.DeserializeObject<Model.Result>(result);
} else if (response == null)
{
// Show alert for failed calls
Model.Result nullResult = new Model.Result { ResultCode = 200, ResultData = "", ResultFlag = false, ResultValue = "Bağlantı Kesildi." };
return nullResult;
}
}
catch (Exception ex)
{
Model.Result nullResult = new Model.Result { ResultCode = 0, ResultData = "", ResultFlag = false, ResultValue = $"Bağlantı kesildi. Sistem Mesajı: \r\n{ex.Message}" };
Console.WriteLine(ex.Message);
return nullResult;
throw;
}
发帖方法:
try
{ // http client oluşturma
HttpClient client = new HttpClient();
//Client Adres
var baseUrl= Preferences.Get("URL", "");
string url = $"http://" + baseUrl+ "/samplePost";
// Jsona dönüştürülecek object
// Object to json
string json = JsonConvert.SerializeObject(apiParameter);
var content = new StringContent(json, Encoding.UTF8, "application/json");
// Post methodu
var postData = await client.PostAsync(url, content);
// Read response from post
var result = await postData.Content.ReadAsStringAsync();
// Json Convert
return JsonConvert.DeserializeObject<Model.Result>(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
有一个简单的例子:
var client = new HttpClient();
client.BaseAddress = new Uri("localhost:8080");
string jsonData = @"{""username"" : ""myusername"", ""password"" : ""mypassword""}"
var content = new StringContent (jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("/foo/login", content);
// this result string should be something like: "{"token":"rgh2ghgdsfds"}"
var result = await response.Content.ReadAsStringAsync();
注:
其中
/foo/login
需要指向您的 HTTP 资源。例如,如果您有一个带有 Login 方法的 AccountController,那么您可以使用类似 /foo/login
的内容来代替 /Account/Login
。