我还需要使用 C# 来执行此操作,并且一直在尝试使用 HttpWebRequest。我要调用的非 .NET SOAP Web 服务也需要小写的 Connection: keep-alive。
我宁愿不为此做套接字编程,所以如果你对如何解决这个问题有任何建议,如果你这样做了,那将非常有帮助。
到目前为止我的调查:
使用 http 协议 1.1 版时,即使您指定了属性,也不会发送标头。
例如
var request = (HttpWebRequest)WebRequest.Create(Endpoint);
request.KeepAlive = true;
解决方案是使用 System.Reflection 来修改 httpBehaviour,这意味着发送 Keep-Alive。这将在每个请求上发送一个初始的大写 K 和 A 'Keep-Alive'。
var sp = request.ServicePoint;
var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
prop.SetValue(sp, (byte)0, null);
我也尝试使用 System.Reflection 来修改标题。下面的代码将以小写正确添加标志:
request.Headers.GetType().InvokeMember("ChangeInternal", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, Type.DefaultBinder, request.Headers, new object[] { "Connection", "keep-alive" });
但是,在我调用 GetResponse 时
var response = (HttpWebResponse)request.GetResponse()
标题被清除。查看 HttpWebRequest.cs 的源代码,这发生在将标头发送到线路之前。
//
// The method is called right before sending headers to the wire*
// The result is updated internal _WriteBuffer
//
// See ClearRequestForResubmit() for the matching cleanup code path.
//
internal void SerializeHeaders() {
....
....
string connectionString = HttpKnownHeaderNames.Connection;
if (UsesProxySemantics || IsTunnelRequest ) {
_HttpRequestHeaders.RemoveInternal(HttpKnownHeaderNames.Connection);
connectionString = HttpKnownHeaderNames.ProxyConnection;
if (!ValidationHelper.IsBlankString(Connection)) {
_HttpRequestHeaders.AddInternal(HttpKnownHeaderNames.ProxyConnection, _HttpRequestHeaders[HttpKnownHeaderNames.Connection]);
}
}
else {
_HttpRequestHeaders.RemoveInternal(HttpKnownHeaderNames.ProxyConnection);
}
RemoveInternal 还将删除我们使用反射入侵的标头。
所以这仍然让我陷入困境。
除了在套接字级别上,还有其他方法吗?
是否有其他类或 3rd 方库允许我根据需要修改标头?
对不起,这不是一个答案,但我还不能评论你的问题。