有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Apache HttpClient和自定义端口

我使用的是ApacheHttpClient 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);

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


共 (2) 个答案

  1. # 1 楼答案

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

    因此,自定义端口可以使用上述代码

  2. # 2 楼答案

    另一种方法是将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,这是错误的