【问题标题】:Xamarin native shared project HttpClient does not workXamarin 本机共享项目 HttpClient 不起作用
【发布时间】:2016-07-27 13:21:07
【问题描述】:

我创建了支持 Android 和 iOS 移动平台的 Xamrin 原生共享项目。我想在这两个移动应用程序中使用 REST 服务。如果我使用 HttpClient 向 REST API 发出请求,则它不起作用。给我的回应是:

{StatusCode:404,ReasonPhrase:“未找到”,版本:1.1,内容: System.Net.Http.StreamContent,标头:{ 变化:接受编码 服务器:DPS/1.0.3 X-SiteId:1000 Set-Cookie:dps_site_id=1000;路径=/ 日期:2016 年 7 月 27 日,星期三,格林威治标准时间 12:09:00 连接:保持活动 内容类型:文本/html; charset=utf-8 内容长度:964 }} 内容:{System.Net.Http.StreamContent} 标头:{变化: 接受编码服务器:DPS/1.0.3 X-SiteId:1000 Set-Cookie: dps_site_id=1000;路径=/ 日期:格林威治标准时间 2016 年 7 月 27 日星期三 12:09:00 连接:保持活动 } IsSuccessStatusCode:false ReasonPhrase: “未找到”状态码:System.Net.HttpStatusCode.NotFound 版本: {1.1} 非公共成员:

如果我使用 HttpWebResponse 发出请求,它会成功获取数据。

你能告诉我为什么 HttpClient 不工作吗?

    // Using HttpClient
    public async Task<string> GetCategories11(string token)
    {
        using (HttpClient client = new HttpClient())
        {
            var url = string.Format("{0}{1}", BaseUrl, CategoriesEndPoint);
            var uri = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            try
            {
                using (var response = await client.GetAsync(uri))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var contentStr = await response.Content.ReadAsStringAsync();
                        return contentStr;
                    }
                    else
                        return null;
                }
            }
            catch
            {
                return null;
            }
        }
    }

    // Using HttpWebRequest
    public async Task<ResponseModel> GetCategories(string token)
    {
        // Create an HTTP web request using the URL:
        var url = string.Format("{0}{1}", RequestClient.BaseUrl, CategoriesEndPoint);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Headers.Add("Authorization", "Bearer " + token);
        request.Accept = "application/json";
        request.Method = "GET";

        try
        {
            // Send the request to the server and wait for the response:
            using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
            {
                // Get a stream representation of the HTTP web response.
                using (Stream stream = response.GetResponseStream())
                {
                    // Use this stream to build a JSON object.
                    JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                    return new ResponseModel() { Success = true, ResponseValue = jsonDoc.ToString(), StatusCode = response.StatusCode };
                }
            }
        }
        catch (WebException ex)
        {
            using (var stream = ex.Response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                return new ResponseModel() { ResponseValue = reader.ReadToEnd(), StatusCode = ((HttpWebResponse)ex.Response).StatusCode };
            }
        }
        catch (Exception ex)
        {
            return new ResponseModel() { ResponseValue = ex.Message };
        }
    }

【问题讨论】:

    标签: xamarin.ios xamarin.android dotnet-httpclient system.net.httpwebrequest


    【解决方案1】:

    调试并暂停在线using (var response = await client.GetAsync(uri)) uri 是什么?和GetCategories()中的一样吗?

    如果您愿意,这是我在 Xamarin.Android 中使用的方法,它适用于不记名令牌。根据您的需要进行更改,您可能不需要执行JsonConvert.DeserializeObject() 部分。

    protected async Task<T> GetData<T>(string dataUri, string accessToken = null, string queryString = null)
    {
        var url = baseUri + "/" + dataUri + (!string.IsNullOrEmpty(queryString) ? ("?" + queryString) : null);
        try
        {
            using (var httpClient = new HttpClient() { Timeout = new TimeSpan(0, 0, 0, 0, SharedMobileHelper.API_WEB_REQUEST_TIMEOUT) })
            {
                // Set OAuth authentication header
                if (!string.IsNullOrEmpty(accessToken))
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    
                using (HttpResponseMessage response = await httpClient.GetAsync(url))
                {
                    string content = null;
                    if (response != null && response.Content != null)
                        content = await response.Content.ReadAsStringAsync();
    
                    if (response.StatusCode == HttpStatusCode.OK ||
                        response.StatusCode == HttpStatusCode.Created)
                    {
                        if (content.Length > 0)
                            return JsonConvert.DeserializeObject<T>(content);
                    }
                    else if (response.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        throw new Exception("Internal server error received (" + url + "). " + content);
                    }
                    else
                    {
                        throw new Exception("Bad or invalid request received (" + url + "). " + content);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error("Could not fetch data via GetData (" + url + ").", ex.ToString());
            throw ex;
        }
        return default(T);
    }
    

    【讨论】:

    • @GoNeale, 调试并暂停 我得到的回复已添加到我的问题下:“给我回复为:”。 什么是uri?它与 HttpClient 方法中的 GetCategories()? 相同 var uri = new Uri(url);使用 (var response = await client.GetAsync(uri)) 在 HttpWebRequest 方法 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url)); 两者都是一样的。跨度>
    • @GoNeale, 如果我直接传递 url,则响应是相同的,而不是传递 uri。不过我会试试你的代码 sn-p。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多