【发布时间】:2018-06-28 08:22:15
【问题描述】:
我正在尝试通过传递服务 url 和 json 参数来获取 API 响应。 Url 和 Parameter 正确传递给 requestAPI 函数,但没有从 PostAsync 方法给出响应。 Url 是 API 位置,参数是 Category Id。当我在浏览器中运行相同的 API 时,它会给出正确的响应。但不是在应用程序中。
这是 requestAPI 函数。
public async Task<ResponseObject> requestAPI(string urlString, string jsonParameters)
{
await Task.Delay(2000); // NOTE: just to simulate a HTTP request over the wire
try
{
var json = JsonConvert.SerializeObject(jsonParameters);
HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
if (true) // no issue here.
{
response = await client.PostAsync(urlString, httpContent);
}
else
{
response = await client.PutAsync(urlString, httpContent);
}
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(@" TodoItem successfully saved.");
var returnVal = await response.Content.ReadAsStringAsync();
return new ResponseObject{
jsonString = returnVal,
isSuccess = true,
error = null
};
}
else
{
return new ResponseObject
{
jsonString = null,
isSuccess = false,
error = null
};
}
}
catch (Exception ex)
{
Debug.WriteLine(@" ERROR {0}", ex.Message);
return new ResponseObject
{
jsonString = null,
isSuccess = false,
error = null
};
}
}
Category Id 来自这个方法。
private async void loadBookList(string categoryId)
{
IsBusy = true;
if (CrossConnectivity.Current.IsConnected)
{
ResponseObject responseObject = await _apiService.requestAPI("http://192.168.0.35/kiyawamu-api/index.php/rest/V1/mobileappintegration/getbookdetailsbycategory", Convert.ToString(categoryId));
if (responseObject.isSuccess)
{
var jsonObject = JsonConvert.DeserializeObject<BookListJsonObject>(responseObject.jsonString);
CategoryBooks = new ObservableCollection<Book>(jsonObject.booksByCategory);
}
else
{
giveAlertForCommonError();
}
}
}
我尝试了以下解决方案,但不起作用。
- Url 用作 uri
var uri = new Uri(urlString); - jsonParameter 也用作字符串
- GetAsync 也使用过
对此的任何帮助将不胜感激。
【问题讨论】:
-
安卓还是iOS?此代码是否在 PCL 中?
-
but doesn't give response from PostAsync method这是什么意思,你得到什么状态码。你怎么称呼这个 -
此代码在 PCL @Daniel 中。我只运行 Android 项目。
-
运行调试器时,它会给出响应 ->
response = {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent@TheGeneral -
这是XY problem。它确实返回响应。 Not Found 是一个响应。检查响应的正文,看看是否有关于请求的消息。
标签: c# json xamarin.forms async-await httpclient