[英]Proper way constructing a POST body data in Application/x-www-form-urlencoded using C# HttpWebRequest
[英]Is there a way to pass this contenttype "application/x-www-form-urlencoded;v=2.0" in C#?
我试图在 C# 中复制 CURL 中的以下代码。 请注意,此代码与 curl 一起正常工作。 我正在使用这个https://curl.olsh.me/创建请求。
curl -k -u "默认用户:机器人" -H "内容类型:application/x-www-form-urlencoded;v=2.0" -d "value=TRUE" " https://localhost/rw/rapid/符号/RAPID/T_ROB1/EGMDemo/run_egm/data?mastership=implicit ”
我试图将此命令转换为 c# 并在到达该行时:
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded;v=2.0");
我收到一个异常,即application/x-www-form-urlencoded;v=2.0无效。 如何传递此内容类型? 如果使用 httpclient 无法实现,还有其他方法可以做到吗?
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true;
using (var httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://localhost/rw/rapid/symbol/RAPID/T_ROB1/EGMDemo/run_egm/data?mastership=implicit"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("Default User:robotics"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("value=TRUE");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded;v=2.0");
var response = await httpClient.SendAsync(request);
}
}
可以尝试直接使用request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded;v=2.0");
MediaTypeHeaderValue
仅支持为 HTTP/1.1 定义的标准媒体类型
编辑错误:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.