Apache HttpClient和自定义端口

Ste*_*han 3 java apache-httpclient-4.x

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

HttpPost post = new HttpPost("http://myserver.com:50000");
HttpResponse response = httpClient.execute(post);
Run Code Online (Sandbox Code Playgroud)

如果没有定义端口,则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);
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*s G 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);
Run Code Online (Sandbox Code Playgroud)

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

  • 如果您收到"400错误请求",则表示您实际连接到服务器,发送请求并获得响应.检查服务器日志以查看问题所在. (4认同)