2017-04-20 142 views
0

我正在嘗試從API中獲取REST數據,但我需要使用某些服務器端解決方案來處理對API的調用。我曾嘗試使用以下代碼如何使用ASP.NET MVC從服務器端調用API?

try 
{ 
    HttpClient client = new HttpClient(); 
    client.Timeout = TimeSpan.FromSeconds(60); 

    var request = new HttpRequestMessage() 
    { 
     RequestUri = new Uri(string.Format("https://jsonodds.com/{0}{1}{2}", "api/odds/", "?source=", "3")), 
     Method = HttpMethod.Get, 
    }; 

    request.Headers.Add("JsonOdds-API-Key", "your key"); 

    HttpResponseMessage response = client.SendAsync(request).Result; 

    if (response.IsSuccessStatusCode) 
    { 
     String.Format("Success"); 
    } 
} 
catch (Exception ex) 
{ //log error } 

我收到407()錯誤。任何想法或提示如何做到這一點?

+5

'407' =「HTTP錯誤407需要代理驗證」<=似乎您的憑證沒有按順序。 – Igor

回答

1

如果您正在瀏覽代理服務器,那麼您需要爲HttpClient使用不同的構造函數。

 _httpClient = new HttpClient(new HttpClientHandler 
      { 
       UseProxy = true, 
       Proxy = new WebProxy 
       { 
        Address = new Uri(proxyUrl), 
        BypassProxyOnLocal = false, 
        UseDefaultCredentials = true 
       } 
      }) 
      { 
       BaseAddress = url 
      }; 

將proxyUrl替換爲您的代理地址,然後將該憑證替換爲對您的代理有效的憑證。此示例使用默認憑據,但可以將NetworkCredential傳遞給WebProxy。