Apache HttpClient和自定义端口

问题描述 投票:3回答:3

我正在使用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);

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

java apache-httpclient-4.x
3个回答
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
投票

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

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


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)的问题,只能在路径后面找到您的端口,例如:http://localhost/api:8080,这是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.