[英]how to add 'Content-Type' header in (HTTP GET) Rest request header collection using HttpClient?
I am using HttpClient for rest service . 我正在使用HttpClient进行休息服务。 At at one point I have a problem when I try to add "Content-Type" in my 'Get' request header .
当我尝试在“Get”请求标头中添加“Content-Type”时,我有一个问题。
I know "Content-Type" is suitable for content send in request body part But It's my need i have to send "Content-Type" with request header part. 我知道“Content-Type”适用于请求正文部分发送的内容但是我需要发送带有请求标题部分的“Content-Type”。
I also try to remove "Content-Type" header from Invalid Header list of HttpRequestHeaders 我还尝试从HttpRequestHeaders的 Invalid Header列表中删除“Content-Type”标头
I find link How do you set the Content-Type header for an HttpClient request? 我找到链接如何为HttpClient请求设置Content-Type标头?
Dim field = GetType(System.Net.Http.Headers.HttpRequestHeaders).GetField("invalidHeaders", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.[Static])
If field IsNot Nothing Then
Dim invalidFields = DirectCast(field.GetValue(Nothing), HashSet(Of String))
invalidFields.Remove("Content-Type")
End If
But my issue not resolved I have exception 但我的问题没有解决,我有例外
InnerException: 的InnerException:
Message=The 'content-type' header must be modified using the appropriate property or method. Message =必须使用适当的 属性或方法 修改“content-type”标头 。
StackTrace:
at System.Net.WebHeaderCollection.ThrowOnRestrictedHeader(String headerName)
at System.Net.WebHeaderCollection.Add(String name, String value)
at System.Net.Http.HttpClientHandler.SetRequestHeaders(HttpWebRequest webRequest, HttpRequestMessage request)
at System.Net.Http.HttpClientHandler.CreateAndPrepareWebRequest(HttpRequestMessage request)
at System.Net.Http.HttpClientHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
InnerException:
I find some tools like Postman or SoupUI allow this . 我发现像Postman或SoupUI这样的工具允许这样做。
Please help me to find some solution . 请帮我找一些解决方案。
Thanks 谢谢
HttpWebRequest may come to your rescue. HttpWebRequest可能会帮您解决问题。
private static string CallService(string url)
{
WebRequest req = WebRequest.Create(url);
req.Method = "GET";
String json;
req.ContentType = "application/json; charset=utf-8";
var resp = req.GetResponse();
using (varstream = resp.GetResponseStream())
{
var re = new StreamReader(stream);
json = re.ReadToEnd();
}
return json;
}
}
Async implementation of this can be found from Getting the Response of a Asynchronous HttpWebRequest 可以从获取异步HttpWebRequest的响应中找到异步实现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.