UnknownHostException 在java应用程序中,在Postman中没有问题



我正在尝试在Java应用程序中访问互联网上的API。但是,我得到了一个UnknownHostException例外。

如果我使用邮递员点击相同的 API,我会正确获得结果。

我已经尝试了在互联网上发现的几件事,例如在执行 java 应用程序时指定代理:

-Dhttp.proxyHost=<some_proxy_url> -Dhttp.proxyPort=80 -Dhttps.proxyHost=<some_proxy_url> -Dhttps.proxyPort=80 -Dhttps.proxySet=true -Dhttp.proxySet=true

但这对我根本没有帮助。

这是我必须执行请求的代码:

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpRequestBase request = new HttpPost(
"https://some-host.com/some-api");
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
} catch (IOException e) {
e.printStackTrace();
}

这是异常的完整堆栈跟踪:

java.net.UnknownHostException: some-host.com: nodename nor servname provided, or not known
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
at java.net.InetAddress.getAllByName0(InetAddress.java:1276)
at java.net.InetAddress.getAllByName(InetAddress.java:1192)
at java.net.InetAddress.getAllByName(InetAddress.java:1126)
at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:112)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:373)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:394)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at App.connect(App.java:25)
at App.main(App.java:15)

我注意到我的机器之外的任何主机都有问题。我什至尝试过使用www.google.com主机,但得到了同样的例外。

但是,如果我使用本地主机的API,则没有任何问题。

我错过了什么?

根据上面的评论,听起来您尝试访问的应用程序端点只能通过 Postman 配置为使用的代理获得,而使用 Apache HTTPClient 的 Java 应用程序目前不是。

在发出请求之前,您应该能够通过执行以下操作来配置 HTTPClient 以使用代理:

HttpHost target = new HttpHost("some-host.com", 443, "https");
HttpHost proxy = new HttpHost("<your-proxy-host>", /* proxy-port */, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet request = new HttpPost("/some-api");
request.setConfig(config);
CloseableHttpResponse response = httpclient.execute(target, request);

最新更新