我试图编写一个程序,它只是通过http / s将文件从一个文件发送到一个Web服务,然后得到一个响应。我得到的错误是:
"底层连接已关闭:无法为SSL / TLS安全通道建立信任关系。 ---> System.Security.Authentication.AuthenticationException:根据验证程序,远程证书无效。"
有什么想法吗?可能是服务器。
以下代码是我的程序
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace XmlSender
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Please enter the URL to send the XML File");
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Console.ReadLine());
byte[] bytes;
Console.WriteLine("Please enter the XML File you Wish to send");
bytes = Encoding.ASCII.GetBytes(Console.ReadLine());
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
}
requestStream.Close();
}
catch (Exception e)
{
Console.WriteLine("An Error Occured" + Environment.NewLine + e);
Console.ReadLine();
}
}
}
}
答案 0 :(得分:1)
试试这段代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace XMLSender
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Please enter the URL to send the XML File");
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Console.ReadLine());
byte[] bytes;
Console.WriteLine("Please enter the XML File you Wish to send");
bytes = Encoding.UTF8.GetBytes(Console.ReadLine());
request.Headers.Add("Content-Encoding", "utf-8");
request.ContentLength = bytes.Length;
request.UserAgent = @"Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36";
request.Method = "POST";
request.Timeout = 20000;
request.KeepAlive = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("An Error Occured" + Environment.NewLine + e);
Console.ReadLine();
}
}
}
}