我有以下可以使用的Curl Call。
curl --insecure --user user@applicationname:password "https://someURL"
我不能为我的生活让HttpWebRequest模仿这个。
目前正在尝试
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://someURL);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "*/*";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("USER@Account:Password"));
我收到错误身份验证失败,因为远程方已关闭传输流
我猜这与使用不安全选项的curl命令有关,但我不能在我的生活中看到如何在请求中执行此操作。
做网络限制/政策我无法下载restSharp或任何其他第三方库...
答案 0 :(得分:2)
在执行请求之前添加此行
System.Net.ServicePointManager.ServerCertificateValidationCallback = (obj, X509certificate, chain, errors) => true;
答案 1 :(得分:2)
我最终使用了HttpClient。结合使用从上面的@Alberto Monteiro获得的信息,我能够使我的代码按预期工作。
string url = Request.Form["Url"];
using (var client = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
ServicePointManager.ServerCertificateValidationCallback = (obj, x509Certificate, chain, errors) => true;
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/xml"));
var byteArray = Encoding.ASCII.GetBytes(Request.Form["User"] + "@ACCOUNT:" + Request.Form["Pass"]);
var header = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
var response = client.GetAsync(url).Result;
HttpContent content = response.Content;
string result = content.ReadAsStringAsync().Result;
}