我在发送POST请求并获得响应时遇到问题。我已经制作了本地PHP脚本,该脚本返回了一些字符串值,但我无法使其与Xamarin一起使用。
这是我用来发送请求的方法:
public async Task<string> Post_Request()
{
var request = new HttpRequestMessage();
request.RequestUri = new Uri("http://localhost/server.php");
request.Method = HttpMethod.Post;
request.Headers.Add("Accept", "application/json");
var client = new HttpClient();
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(continueOnCapturedContext: false);
if (response.StatusCode == HttpStatusCode.OK)
{
return "OK";
}
else
{
return "BAD!";
}
}
调试时,程序不会在“ if(res(seponse.StatusCode == HttpStatusCode.OK)”条件下进入if或else代码分支。
这是我的PHP脚本:
<?php
return
"
{
"user":"01",
"name":"ime"
}
"
//echo "OK";
?>
答案 0 :(得分:0)
这是我使用的示例发帖请求。
var objRequest = new CustomerDetailsRequest() {
customerId = 1
};
string url = $"/api/v1/CustomerDetails";
var requestBody = await Task.Run(() => JsonConvert.SerializeObject(objRequest));
using (var httpClient = new HttpClient())
{
CustomerDetailsResponse data = new CustomerDetailsResponse();
try
{
httpClient.BaseAddress = new Uri("http://localhost:3000");
var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
var result = await httpClient.PostAsync(url, content);
var response = await result.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<CustomerDetailsResponse>(response);
if (result.IsSuccessStatusCode && result.StatusCode == HttpStatusCode.OK)
{
return data;
}
return null;
}
catch (Exception exp)
{
return null;
}
}
让我知道这是否令人困惑