[英]Setting REQUEST header Http Client vb.net
考慮下面的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.
Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
。
我在Google各處搜索了一種將請求標頭設置為JSON的方法。 使用提琴手(在服務器上),我可以看到請求以純文本/文本形式發送。
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
Content-Type: text/plain; charset=utf-8
這是我遇到的問題。 由於請求的主體是JSON,因此需要將其設置為JSON的內容類型。 如何在vb.net代碼中將此content-type
設置為JSON。
我找到了解決方案,我不知道這是正確的解決方案還是有更好的解決方案。
基本上,您需要在要發送的實際內容上而不是在HTTP客戶端上設置content-type
標頭。
因此,基本上在代碼中添加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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.