如何覆盖“主机”?使用Apache commons HttpClient时请求中的标头 [英] How can I override the "Host" header in the request when using Apache commons HttpClient

查看:106
本文介绍了如何覆盖“主机”?使用Apache commons HttpClient时请求中的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jakarta Commons HttpClient 3.1编写一个负载测试工具,该工具需要针对不同的服务器,并假装它针对HTTP服务器中的正确虚拟主机。为此,我需要能够将请求中的主机HTTP标头设置为不同的主机名,然后是我要连接的实际主机名。

I am using Jakarta Commons HttpClient 3.1 writing a load test tool that needs to target different servers and pretend like it targeted the correct virtual host in the HTTP server. For that I need to be able to set the "Host" HTTP header in the request to a different host name then the actual host name that I'm connecting to.

似乎很明显我应该使用 Method.setRequestHeader(Host,fakehostname),但是HttpClient只是忽略了这一点并且总是发送我正在连接的真实主机名在主机标题中(我已启用httpclient.wire的调试日志记录,我可以专门执行此操作)。

It seemed pretty obvious that I should use Method.setRequestHeader("Host","fakehostname"), but HttpClient just ignores this and always sends the real host name I'm connecting to in the "Host" header (I've enabled debug logging for "httpclient.wire" and I can it does this specifically).

如何覆盖标题那么HttpClient注意了吗?

How can I override the header so that HttpClient takes heed?

推荐答案

在搜索了一些,并从Oleg的答案中得到一个提示后,我找到了方法 HttpMethodParams :: setVirtualHost()

After searching some more, and taking a hint from Oleg's answer, I've found the method HttpMethodParams::setVirtualHost().

当HttpClient格式化请求时,它总是在发送请求之前自己创建主机标头 - 因此它不能被覆盖为标准标头。但是,在从URL生成Host标头的主机名之前,HttpClient会检查HttpMethodParams对象以查看用户是否要覆盖主机名。这只会覆盖主机名而不是端口,所以它更容易使用,虽然不像我想的那样直观。

when HttpClient formats a request, it always creates the "Host" header itself just before sending the request - so it cannot be overridden as a standard header. But before the host name for the "Host" header is generated from the URL, HttpClient checks the HttpMethodParams object to see if the user wants to override the host name. This only overrides the host name and not the port so it would be easier to use, though not as intuitive as I'd like.

使用它的代码可以看起来像这样:

The code to use this can look like this:

Method m = new GetMethod("http://some-site/some/path");
m.getParams().setVirtualHost("some-other-site");
client.executeMethod(m);

因为我喜欢一个衬垫,所以这也可以写成:

Because I like one liners, this can also be written as:

client.executeMethod(new GetMethod("http://some-site/some/path") {{
    getParams().setVirtualHost("some-other-site"); }});

这篇关于如何覆盖“主机”?使用Apache commons HttpClient时请求中的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆