0

Android および iOS モバイル プラットフォームをサポートする Xamrin ネイティブ共有プロジェクトを作成しました。両方のモバイル アプリで REST サービスを利用したいと考えています。HttpClient を使用して REST API にリクエストを行うと、機能しません。次のように応答します。

{StatusCode: 404、ReasonPhrase: 'Not Found'、バージョン: 1.1、コンテンツ: System.Net.Http.StreamContent、Headers: { Vary: Accept-Encoding Server: DPS/1.0.3 X-SiteId: 1000 Set-Cookie: dps_site_id=1000; path=/ Date: Wed, 27 Jul 2016 12:09:00 GMT Connection: keep-alive Content-Type: text/html; charset=utf-8 Content-Length: 964 }} Content: {System.Net.Http.StreamContent} Headers: {Vary: Accept-Encoding Server: DPS/1.0.3 X-SiteId: 1000 Set-Cookie: dps_site_id=1000 ; path=/ Date: Wed, 27 Jul 2016 12:09:00 GMT Connection: keep-alive } IsSuccessStatusCode: false ReasonPhrase: "Not Found" StatusCode: 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 };
        }
    }
4

1 に答える 1

0

デバッグしてオンラインで一時停止する と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);
}
于 2016-07-28T02:31:55.417 に答える