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

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

4

3 回答 3

9

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

不能保证这会奏效,但请尝试一下。

于 2011-10-10T12:45:00.280 回答
1

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

所以自定义端口确实适用于上述代码。

于 2011-10-11T19:40:39.037 回答
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 构造 aHttpPost和调用的问题httpClient.execute(host, httpPost, handler, context),只发现您的端口附加路径之后,例如:http://localhost/api:8080,这是错误的。

于 2019-03-28T11:40:59.127 回答