HttpWebRequest不起作用,但Postman确实如此

时间:2018-06-06 18:47:03

标签: c# .net httpwebrequest webclient

我正在尝试使用下面的代码通过WebHttpRequest获取一个json字符串(它试图调用一个文件,它将为我返回应用程序中的json)。它在我的机器上运行但是当我部署到用户服务器时,我收到了错误

  

“基础连接已关闭:发生意外错误   发送。“。

当我尝试为URL运行powershell invoke-webrequest时出现了同样的错误,但奇怪的是,当我在用户服务器内部或外部使用Postman(获取或发布)URL时,它工作正常。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/json";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
String jsonResponse = reader.ReadToEnd();

我还尝试使用另一种方法(WebClient)来获取URL,但它也没有用。

String jsonResponse = null;
using (var webClient = new WebClient())
{
    jsonResponse = webClient.DownloadString(url);
}

我在异常时遇到的完整错误:

  

远程服务器返回错误:(401)未经授权。   系统      在System.Net.HttpWebRequest.GetResponse()

有没有人有任何想法?

谢谢。

1 个答案:

答案 0 :(得分:1)

我认为这可能是你的情况"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

您似乎需要设置ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

BTW,你的代码:

request.UseDefaultCredentials = true; request.PreAuthenticate = true; request.Credentials = CredentialCache.DefaultCredentials;

那凭证是什么?这是AD凭证之类的网络凭证吗?是否有授权访问该服务器?

相关问题