.net 如何强制HttpClient发送连接头?
默认情况下,HttpClient不发送连接保持活动标头。我怎样才能强迫它这样做?我很确定这需要通过反思来实现,但不确定如何实现 类似于下面的问题,但我想知道如何强制HttpClient而不是HttpWebRequest 我需要使用HTTP1.1,所以切换到1.0不是一个选项 编辑1:根据需要添加代码样本.net 如何强制HttpClient发送连接头?,.net,vb.net,http-headers,dotnet-httpclient,.net,Vb.net,Http Headers,Dotnet Httpclient,默认情况下,HttpClient不发送连接保持活动标头。我怎样才能强迫它这样做?我很确定这需要通过反思来实现,但不确定如何实现 类似于下面的问题,但我想知道如何强制HttpClient而不是HttpWebRequest 我需要使用HTTP1.1,所以切换到1.0不是一个选项 编辑1:根据需要添加代码样本 Public Overridable Async Function WebRequestAsync(Url As String, Optional RequestMethod As Requ
Public Overridable Async Function WebRequestAsync(Url As String, Optional RequestMethod As RequestMethod = RequestMethod.GET, Optional Content As Object = Nothing, _
Optional ContentType As ContentType = ContentType.Default, Optional Accept As String = DefaultAcceptString, _
Optional AdditionalHeaders As NameValueCollection = Nothing, Optional Referer As String = Nothing, _
Optional NoCache As Boolean = False, Optional CustomCookieHandler As Boolean = False, _
Optional OutputBufferKey As String = Nothing, Optional CancellationToken As CancellationToken? = Nothing, _
Optional Attempts As Integer = 2, Optional CanBeCancelled As Boolean = True) _
As Tasks.Task(Of HttpResponseMessage)
If OutputBufferKey Is Nothing Then OutputBufferKey = Me.OutputBufferKey
If CancellationToken Is Nothing Then CancellationToken = Me.CancellationToken
If TypeOf Content Is PostData Then Content = Content.ToString
If Attempts < 1 Then Attempts = 1
Dim Method As HttpMethod = Nothing
Select Case RequestMethod
Case Variables.RequestMethod.DELETE : Method = HttpMethod.Delete
Case Variables.RequestMethod.GET : Method = HttpMethod.Get
Case Variables.RequestMethod.OPTIONS : Method = HttpMethod.Options
Case Variables.RequestMethod.POST : Method = HttpMethod.Post
Case Variables.RequestMethod.PUT : Method = HttpMethod.Put
End Select
'prepare message
Dim Message As New HttpRequestMessage(Method, Url)
Message.Headers.ExpectContinue = False
If Accept IsNot Nothing Then Message.Headers.TryAddWithoutValidation("Accept", Accept)
If Referer IsNot Nothing Then Message.Headers.Add("Referer", Referer)
If NoCache Then
Message.Headers.Add("Pragma", "no-cache")
Message.Headers.Add("Cache-Control", "no-cache")
End If
If AdditionalHeaders IsNot Nothing Then
For Each Key In AdditionalHeaders.AllKeys
Message.Headers.TryAddWithoutValidation(Key, AdditionalHeaders(Key))
Next
End If
'set content
If RequestMethod = Variables.RequestMethod.POST Then
Dim ContentTypeString As String = GetEnumDescription(ContentType)
Dim ContentBytes As Byte() = New Byte() {}
If Content IsNot Nothing Then
If TypeOf Content Is String Then
ContentBytes = Encoding.UTF8.GetBytes(CType(Content, String))
ElseIf TypeOf Content Is Byte() Then
ContentBytes = CType(Content, Byte())
ElseIf TypeOf Content Is MultiPartPostData Then
Dim MultiPartPostData As MultiPartPostData = CType(Content, MultiPartPostData)
ContentBytes = MultiPartPostData.Bytes
ContentTypeString += "; boundary=" & MultiPartPostData.Boundary
End If
End If
Dim ByteArrayContent As New ByteArrayContent(ContentBytes)
ByteArrayContent.Headers.Add("Content-Type", ContentTypeString)
Message.Content = ByteArrayContent
End If
Output(OutputBufferKey, RequestMethod.ToString & " " & Url, OutputType.Debug)
'Set cancellation token
Dim TimeoutToken As New CancellationTokenSource
If CancellationToken IsNot Nothing AndAlso CancellationToken.HasValue AndAlso CanBeCancelled Then TimeoutToken = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken.Value)
TimeoutToken.CancelAfter(CInt(DefaultTimeout * 1.2))
'get response
Dim Response As HttpResponseMessage = Nothing
For Attempt = 1 To Attempts
Try
Response = Await Client.SendAsync(Message, HttpCompletionOption.ResponseContentRead, TimeoutToken.Token).ConfigureAwait(False)
Catch ex As Exception When TypeOf ex Is HttpRequestException OrElse TypeOf ex Is Tasks.TaskCanceledException
If ex.InnerException IsNot Nothing Then
If DebugMode Then Output(OutputBufferKey, Method.ToString & " " & Url & " " & ex.InnerException.Message, OutputType.Error)
If ex.InnerException.Message = "Timed out" Then Continue For
Else
If DebugMode Then Output(OutputBufferKey, Method.ToString & " " & Url & " " & ex.Message, OutputType.Error)
End If
Catch ex As Exception
If DebugMode Then Output(OutputBufferKey, Method.ToString & " " & Url & " " & ex.Message, OutputType.Error)
End Try
Exit For
Next
If Response IsNot Nothing Then
Output(OutputBufferKey, Method.ToString & " " & Url & " " & Response.StatusCode & " " & Response.StatusCode.ToString, OutputType.Debug)
If CustomCookieHandler AndAlso Cookies IsNot Nothing Then
Dim Values As IEnumerable(Of String) = Nothing
If Response.Headers.TryGetValues("Set-Cookie", Values) Then ManuallyExtractCookies(Values, New Uri(Url).GetLeftPart(UriPartial.Authority))
End If
End If
Return Response
End Function
你能发布你用来发送数据的代码吗?您可能需要一个HttpRequestMessage,您可以在其中设置任何想要的头。@Stefan添加了代码,但据我所知,该头不能手动设置,因为它是一个受限头。设置它的方法是HttpClient的KeepAlive属性。问题是,当设置为true时,只有当设置为false时,才会发送标题。嗯,我明白你的意思,尽管我认为可以使用Message.Headers.Add等设置keep alive。如果没有帮助,反射可能有助于设置一些内部值,但我不知道要设置哪些值。@iguanaman它不会被发送,因为保持活动状态是Http/1.1的默认行为。您不需要为服务器发送保持活动状态标头来保持连接打开。@Darreller谢谢,我知道这一点,但服务器不尊重它,除非出于某种原因发送头。不是我的服务器,所以我唯一的选择是强制发送头。