3

I have a Java application that needs to connect to a remote PostgreSQL database over a VPN. Here is the relevant code:

Class.forName("org.postgresql.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:postgresql://" + sqlHost + ":" + sqlPort + "/mydb", username, password);

This throws the error

org.postgresql.util.PSQLException: FATAL: pg_hba.conf rejects connection for host "172.16.7.5", user "xxxxx", database "xxxxx", SSL off

The Host IP address in sqlHost is actually 192.168.12.55, but if you notice the error message says that it is connecting to host 172.16.7.5 (which is the IP address assigned by the VPN).

I am able to connect to this PostgreSQL database using the exact same connection parameters on the exact same VPN using PGAdmin and using Python's psocopg2 module. Here is the equivalent Python code:

conn = psycopg2.connect("dbname=mydb user="+username+" password="+password+" host="+sqlHost+" port="+sqlPort)

Why in the world is only Java having problems with this? Since the connection works over PGAdmin and Python, I assume there is some setting in Java that I am using incorrectly, but I can't find anything.

EDIT: After reading into PostgreSQL docs a little more, I found that the issue with it listing the wrong hostname is not part of the issue but rather just the way PostgreSQL sees my computer over the VPN. Problem is still not solved, however.

4

2 回答 2

5

好的,我自己解决了这个问题。该问题与 VPN 无关,而是与默认情况下 Java 不尝试任何类型的 SSL 连接而 PGAdmin 和psycopg2这样做的事实有关。

解决方案是将以下参数添加到我的连接 url: ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory

于 2013-08-08T20:08:58.893 回答
2

我不确定这是否是问题所在,但过去我在尝试连接到打开 VPN 的数据库时遇到过类似的问题。

尝试使用在应用程序启动时传递的 JVM 参数运行您的应用程序:

-Djava.net.preferIPv4Stack=true

另请参阅此答案以获得更永久的解决方案。

于 2013-08-08T19:17:02.220 回答