0

AndroidおよびiOSモバイルプラットフォームをサポートするXamrinネイティブ共有プロジェクトを作成しました。私は両方のモバイルアプリでRESTサービスを利用したいと思います。私がHttpClientを使ってREST APIに要求したら、それは動作しません。Xamarinネイティブ共有プロジェクトHttpClientが動作しません

{のStatusCode:404、のreasonPhrase 'が見つかりません'、バージョン:1.1、内容: System.Net.Http.StreamContent、ヘッダ:{ヴァリ:受け入れ-エンコーディングを サーバー:DPSとして私の応答を与えます/1.0.3 X-SiteId:1000セットクッキー:dps_site_id = 1000; path =/ 日付:Wed、27 Jul 2016 12:09:00 GMT接続:キープアライブ コンテンツタイプ:text/html; (Accept-Encoding Server):DPS/1.0.3 X-SiteId:1000セットクッキー: (アクセシビリティエンコーディングサーバー:DPS/1.0.3 X-SiteId:1000セットクッキー:) dps_site_id = 1000; "ReasonPhrase: "が見つかりません "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 }; 
     } 
    } 

答えて

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); 
} 
+0

** @ GoNeale、**デバッグを通って、私は下の私の質問に追加され得る応答は** 一時停止:すでに:「私のような応答を提供します」。 ** uriとは何ですか? GetCategories()と同じですか?** * HttpClientメソッド var uri = new Uri(url); * HttpWebRequestの方法 HttpWebRequestの要求=(HttpWebRequestの)HttpWebRequest.Create(新しいURI(URL))で*(VAR応答= client.GetAsync(URI)を待つ) を使用して、* 両方とも同じです。 – user2618875

+1

** @ GoNeale、** uriを渡す代わりに、urlを直接渡すと応答は同じです。しかし、あなたのコードスニペットを試してみます。 – user2618875

関連する問題