简体   繁体   中英

How do I call API from server side using ASP.NET MVC?

I am trying to pull REST data from an API but I need to handle the calls to the API with some server side solution. I have tried using the following code

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 }

I receive a 407() error. Any ideas or tips how to do this?

If you are going through a proxy server then you need to use a different constructor for HttpClient.

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

Replace proxyUrl with your proxy address then replacing the credential with those that are valid for your proxy. This example uses the default credentials, but you can pass a NetworkCredential to the WebProxy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM