Apache HttpClient和自定义端口

3

我正在使用Apache HttpClient 4,它能正常工作。唯一不正常的事情是自定义端口。似乎只有根目录被获取,端口被忽略。

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

如果没有定义端口,http和https连接将正常工作。 方案注册表定义如下:

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);

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


嗯... 当您的套接字正在侦听端口80和443时,您如何连接到端口50000?难道这不应该是 final Scheme http = new Scheme("http", 50000, PlainSocketFactory.getSocketFactory()); 吗? - Angel O'Sphere
我也曾这样想,但当没有指定端口时,方案端口才是标准。如果已明确设置了端口,则使用该端口而不是方案端口。 - Stephan
1
我遇到了客户端无法处理自定义端口的相同问题。你能举个例子说明一下你是如何使用ByteArrayEntity的吗? - user1040317
3个回答

10

一个建议是尝试使用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);

无法保证这会奏效,但可以尝试一下。


4
如果你看到“400 bad request”错误提示,意味着你已经成功连接到服务器,发送了请求并接收到了响应。请查看你的服务器日志,以确定具体出现了什么问题。 - Aleks G
喜欢这种构建 httpHost 的方式。它将主机地址分离出来,可以像 uri.toURL().toString() 一样获取完整的 URL。此外,在 httpClient.execute(httpHost, httpRequest, handler, context) 中,它使 URL 插值正确。 - WesternGun

2
问题在于服务器不理解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();

通过这种方式,您可以避免使用字符串构造HttpPost和调用httpClient.execute(host, httpPost, handler, context)时出现问题,只发现您的端口附加在路径之后,例如:http://localhost/api:8080,这是错误的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接