考虑以下VB代码:
Public Async Function someFunction(ByVal url As String, Optional ByVal methodPost As Boolean = False, Optional ByVal postContent As HttpContent = Nothing) As Threading.Tasks.Task(Of String)
Using client = New HttpClient
client.DefaultRequestHeaders.Authorization = makeAuthenticationHeader()
If methodPost Then
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim Response = Await client.PostAsync(url, postContent)
Dim content As String = Await Response.Content.ReadAsStringAsync
Return content
Else
Return Await client.GetStringAsync(url)
End If
End Using
End Function
我想将请求内容类型设置为application/json
以及将响应内容类型设置为application/json
。
如果我添加以下代码行:
client.DefaultRequestHeaders.Add("content-type", "application/json")
然后系统抛出异常Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
。
我已经在google上搜索了将请求标头设置为JSON的方法。使用fiddler(在服务器上)我可以看到请求是以普通/文本形式发送的。
POST **URL REMOVED FOR SAFETY REASONS** HTTP/1.1
Authorization: Basic **HASHED AUTH DETAILS - REMOVED FOR SAFETY REASONS**
Accept: application/json
Content-Type: text/plain; charset=utf-8
Host: **HOST REMOVED FOR SAFETY REASONS**
Content-Length: 1532
Expect: 100-continue
Connection: Keep-Alive
Content-Type: text/plain; charset=utf-8
这就是我遇到问题的地方。这需要设置为JSON的内容类型,因为请求的主体是JSON。如何在vb.net代码中将此content-type
设置为JSON。
答案 0 :(得分:0)
我找到了一个解决方案,我不知道它是否是正确的解决方案,或者是否有更好的解决方案。
基本上,您需要在发送的实际内容上设置content-type
标头,而不是在HTTP客户端上。
因此,基本上将content.Headers.ContentType = New MediaTypeWithQualityHeaderValue("application/json")
添加到代码中也应将 REQUEST的内容类型设置为JSON。
Public Async Function someDifferentFunction() As Threading.Tasks.Task(Of String)
Dim url As String = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Dim content As HttpContent = New StringContent(txtRequestBody.Text)
content.Headers.ContentType = New MediaTypeWithQualityHeaderValue("application/json")
Return Await someFunction(url, True, content)
End Function