【问题标题】:Xamarin Forms HttpClient PostAsync does not return responseXamarin Forms HttpClient PostAsync 不返回响应
【发布时间】: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();
                }
            }
        }

我尝试了以下解决方案,但不起作用。

  1. Url 用作 uri var uri = new Uri(urlString);
  2. jsonParameter 也用作字符串
  3. 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


【解决方案1】:

如果您在 Android 上运行它并且代码位于 PCL 中,请尝试添加 ModernHttpClient 以便您可以使用本机 HttpClientHandler。

https://github.com/paulcbetts/ModernHttpClient

但我也建议大家从 PCL 升级到 .NET 标准。如果这样做,则不必安装 NuGet 包即可使用 HttpClient。然后你可以在项目设置中选择 HttpClientHandler 的实现。

【讨论】:

  • 感谢您的回答丹尼尔。但它会给出解决方案吗?那为什么 PostAsync 不返回值呢?
  • ModernHttpClient 已经为我解决了很多次类似的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多