如何从WPF调用HTTPS API

时间:2019-08-27 10:45:35

标签: wpf api https

我正在尝试从WPF应用程序调用https API,但出现此错误:

  

InnerException = {“基础连接已关闭:意外   发送时发生错误。“}消息=”发送时发生错误   请求。”

任何人都可以帮助我到底是什么问题吗?

  private static readonly string apiURL = 
                "https://api.totalsynergy.com/api/v2/Profile/Index";    

  private async Task<bool> GetAuth(string accessToken)
    {
        try
        {
            HttpClient hc = new HttpClient();
            HttpResponseMessage hpm = await hc.GetAsync(apiURL);

            if (hpm.IsSuccessStatusCode)
            {
                var res = await hpm.Content.ReadAsAsync<Organization>();
            }

            return boolValue;
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
            return boolValue;
        }
    }

1 个答案:

答案 0 :(得分:0)

当使用HTTPS时,连接需要某些协议。 在我的示例中,我有一个API URL,可以调用它,并且可以发送一些信息并以JSON接收响应。您可以使它适应您的问题:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

               //get OS version
                var query = "SELECT version FROM Win32_OperatingSystem";
                var searcher = new ManagementObjectSearcher(query);
                var info = searcher.Get().Cast<ManagementObject>().FirstOrDefault();
                string version = info.Properties["Version"].Value.ToString();
                int majorVersion = Int32.Parse(version.Substring(0, version.IndexOf(".")));

                //OS version is windows xp or older
                if (majorVersion < 6)
                {
                    //tls 1.0
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)192;
                }
                else
                {
                    //tls 1.1 or tls 1.2
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                }

                //url to send data
                string url = **YOUR URL**


                //create request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                request.KeepAlive = false;
                request.Timeout = 240000;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = **REQUEST METHOd GET/POST**;

                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";

                //convert to byte stream
                byte[] postBytes = Encoding.UTF8.GetBytes(**Text to send  or empty**);


                //specify content of request - this example is in JSON
                request.ContentType = "application/json";

                if (requestMethod != RequestMethods.GET)
                {

                    request.ContentLength = postBytes.Length;

                    Stream requestStream = request.GetRequestStream();

                    //send
                    requestStream.Write(postBytes, 0, postBytes.Length);

                    requestStream.Close();
                }

                try
                {

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    string result;
                    using (var readers = new StreamReader(response.GetResponseStream()))
                    {
                        return result = readers.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return null;

                }
                finally
                {
                    request.Abort();
                }