如何通过c#使HttpClient获取/发布请求到HTTPS服务器

时间:2018-02-24 16:16:04

标签: c# ssl https httpclient

我有以下工作代码。这仅在服务器是localhost或仅使用HTTP的远程服务器时有效。但是,当我厌倦了HTTPS时,它就会崩溃。我不知道如何向HTTPS服务器发送/获取请求。我知道它涉及SSL认证。整个SSL和认证对我来说都是全新的。所以我尝试了以下几个选项。所以我尝试添加一个生成自签名证书。我通过以下命令制作证书: -

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt

我不知道我是否需要在客户端或服务器端生成此证书?我猜它应该来自Serer方面。我不确定。我从服务器和客户端都尝试过。我得到类似的错误。

private HttpClient GetHttpClient(Uri baseAddress, string path, string apiKey)
        {
            try
            {
                // The path to the certificate.
                string Certificate = "Certificate.crt";
                X509Certificate cert = new X509Certificate(Certificate);
                string resultsTrue = cert.ToString(true);
                WebRequestHandler webRequestHandler = new WebRequestHandler();
                webRequestHandler.ClientCertificates.Add(cert);
                var client = new HttpClient(webRequestHandler);
                client.BaseAddress = baseAddress;
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));

                byte[] key = Convert.FromBase64String(apiKey);
                byte[] pathBytes = Encoding.ASCII.GetBytes(path);
                byte[] hash = Hash(key, pathBytes);
                string encoded = Base64UrlEncode(hash);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", encoded);
                return client;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }

  private async Task<Stream> GetDataAsync(HttpClient client, string path)
        {
            HttpResponseMessage response = null;
            try
            {
                string url = jsonParser.StringBaseAddress + path;
                response = await client.GetAsync(url);
            }
            catch (Exception ex)
            {
                 Console.WriteLine("Msg: "+ex.Message);
                 Console.WriteLine("InnerException. "+ex.InnerException);
            }  
     }

我打电话的时候。我得到以下例外: -

  

Msg:发送请求时发生错误。的InnerException。   System.Net.WebException:底层连接已关闭:可以   不建立SSL / TLS安全通道的信任关系。 ---&GT;   System.Security.Authentication.AuthenticationException:远程   根据验证程序,证书无效。在   System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)at   System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)---   内部异常堆栈跟踪结束--- at   System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
  在System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult)   AR)

如何对HTTPS服务器进行http get / post调用?

0 个答案:

没有答案