Apache HttpClient和自定义端口

时间:2011-10-10 12:09:09

标签: java apache-httpclient-4.x

我正在使用Apache HttpClient 4,它运行正常。唯一不起作用的是自定义端口。似乎提取了根目录并忽略了端口。

HttpPost post = new HttpPost("http://myserver.com:50000");
HttpResponse response = httpClient.execute(post);

如果没有定义端口,http和https-connections运行良好。 方案登记处的定义如下:

final SchemeRegistry sr = new SchemeRegistry();

final Scheme http = new Scheme("http", 80,
      PlainSocketFactory.getSocketFactory());
sr.register(http);

final SSLContext sc = SSLContext.getInstance(SSLSocketFactory.TLS);
  sc.init(null, TRUST_MANAGER, new SecureRandom());
SSLContext.setDefault(sc);

final SSLSocketFactory sf = new SSLSocketFactory(sc,
      SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

final Scheme https = new Scheme("https", 443, sf);
  sr.register(https);

如何为请求定义自定义端口?

3 个答案:

答案 0 :(得分:8)

一个建议是尝试使用HttpPost(URI address)而不是String参数的URI address = new URI("http", null, "my.domain.com", 50000, "/my_file", "id=10", "anchor") HttpPost post = new HttpPost(address); HttpResponse response = httpClient.execute(post); 。您可以显式设置端口:

{{1}}

不能保证这会起作用,但试一试。

答案 1 :(得分:1)

问题是服务器不理解HTTP 1.1分块传输。我使用ByteArrayEntity来缓存数据,一切正常。

所以自定义端口可以使用上面提到的代码。

答案 2 :(得分:0)

另一种方法是将httpClient配置为使用自定义SchemaPortResolver

int port = 8888;
this.httpClient = HttpClients.custom()
        .setConnectionManager(connectionManager)
        .setConnectionManagerShared(true)
        .setDefaultCredentialsProvider(authenticator.authenticate(url,
                port, username, password))
        .setSchemePortResolver(new SchemePortResolver() {
            @Override
            public int resolve(HttpHost host) throws UnsupportedSchemeException {
                return port;
            }
        })
        .build();

这样,您可以避免使用String构造HttpPost并调用httpClient.execute(host, httpPost, handler, context)的问题,只需要在路径的之后处附加端口,例如:{{ 1}},这是错误的。