2017-10-14 5 views
0

REST APIサービスからコンテンツを取得したいと思います。私には私にjsonのコンテンツを返すUriがあります。以下の例のように:C#のREST APIサービスからコンテンツを取得

{ 
    "data": { 
     "id": "2", 
     "type": "people", 
     "attributes": { 
      "email": "[email protected]", 
      "name": "My Name", 
      "gender": "M", 
      "cpf": null, 
      "cnpj": null, 
      "rg": null, 
      "person-type": "NATURAL" 
     } 
    } 
} 

これは私のコードですが、私は内容を得ることができません。誰かが私を助けることができた。私はちょうど私のコードの中でこのコンテンツを取得したい。

async Task InitializeUserData() 
    { 
     var AppToken = Application.Current.Properties["AppToken"]; 
     var AppUid = Application.Current.Properties["AppUid"]; 
     var AppClientHeader = Application.Current.Properties["AppClientHeader"]; 

     using (var client = new HttpClient()) 
     { 
      client.BaseAddress = new Uri("https://api.xxx.com/v1/profile"); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
      client.DefaultRequestHeaders.TryAddWithoutValidation("Access-Token", AppToken.ToString()); 
      client.DefaultRequestHeaders.TryAddWithoutValidation("Client", AppClientHeader.ToString()); 
      client.DefaultRequestHeaders.TryAddWithoutValidation("uid", AppUid.ToString()); 
      HttpResponseMessage response = client.GetAsync("").Result; 

      if (response.IsSuccessStatusCode) 
      { 
       var contents = await response.Content.ReadAsStringAsync(); 
      } 
     } 
    } 
+0

でエラーとは何ですか? – Kzrystof

+0

あなたのjsonは無効です。 – Valkyrie

+0

ベースアドレスは'https://api.xxx.com/v1 'である必要があります。* var response = await client.GetAsync( "profile/2"); * –

答えて

0

あなた必見場所BaseAddress URIの末尾にスラッシュ/、そして次の例のように、あなたの相対URIの初めにスラッシュを置いてはいけません。

client.BaseAddress = new Uri("https://api.xxx.com/v1/profile/"); 
//https://api.xxx.com/v1/profile"/" 

HttpResponseMessage response = client.GetAsync("").Result; 
if (response.IsSuccessStatusCode) 
{ 
    var contents = await response.Content.ReadAsStringAsync(); 
} 

参考MSのドキュメントCalling a Web API From a .NET Client

0

私はあなたのエラーはすでにの世話をしましたが、私はFlurlを見てみることをお勧めしたい参照してください。この要求を書いている間、あなたの人生は楽になり、HttpClientを使ってコードをもっと細かくします(それは流暢な構文なので)。

もっと読む Flurl's github pageFlurl's documentation