多くの場合、Java アプリはインターネットに接続する必要があります。最も一般的な例は、XML ファイルを読み取っていて、そのスキーマをダウンロードする必要がある場合に発生します。
私はプロキシサーバーの背後にいます。プロキシを使用するように JVM を設定するにはどうすればよいですか?
Java ドキュメントから ( javadoc API ではありません):
http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
コマンド ラインで JVM を起動するときに、JVM フラグhttp.proxyHost
を設定します。http.proxyPort
これは通常、シェル スクリプト (Unix の場合) またはバット ファイル (Windows の場合) で行われます。Unix シェル スクリプトの例を次に示します。
JAVA_FLAGS=-Dhttp.proxyHost=10.0.0.100 -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...
JBoss や WebLogic などのコンテナーを使用する場合、私の解決策は、ベンダーが提供する起動スクリプトを編集することです。
多くの開発者は Java API (javadocs) に精通していますが、多くの場合、残りのドキュメントは見過ごされています。多くの興味深い情報が含まれています: http://download.oracle.com/javase/6/docs/technotes/guides/
更新 :プロキシを使用して一部のローカル/イントラネット ホストを解決したくない場合は、@Tomalak からのコメントを確認してください。
http.nonProxyHosts プロパティも忘れないでください。
-Dhttp.nonProxyHosts="localhost|127.0.0.1|10.*.*.*|*.foo.com|etc"
システム プロキシ設定を使用するには:
java -Djava.net.useSystemProxies=true ...
またはプログラムで:
System.setProperty("java.net.useSystemProxies", "true");
ソース: http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html
HTTP/HTTPS や SOCKS プロキシをプログラムで設定するには:
...
public void setProxy() {
if (isUseHTTPProxy()) {
// HTTP/HTTPS Proxy
System.setProperty("http.proxyHost", getHTTPHost());
System.setProperty("http.proxyPort", getHTTPPort());
System.setProperty("https.proxyHost", getHTTPHost());
System.setProperty("https.proxyPort", getHTTPPort());
if (isUseHTTPAuth()) {
String encoded = new String(Base64.encodeBase64((getHTTPUsername() + ":" + getHTTPPassword()).getBytes()));
con.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
Authenticator.setDefault(new ProxyAuth(getHTTPUsername(), getHTTPPassword()));
}
}
if (isUseSOCKSProxy()) {
// SOCKS Proxy
System.setProperty("socksProxyHost", getSOCKSHost());
System.setProperty("socksProxyPort", getSOCKSPort());
if (isUseSOCKSAuth()) {
System.setProperty("java.net.socks.username", getSOCKSUsername());
System.setProperty("java.net.socks.password", getSOCKSPassword());
Authenticator.setDefault(new ProxyAuth(getSOCKSUsername(), getSOCKSPassword()));
}
}
}
...
public class ProxyAuth extends Authenticator {
private PasswordAuthentication auth;
private ProxyAuth(String user, String password) {
auth = new PasswordAuthentication(user, password == null ? new char[]{} : password.toCharArray());
}
protected PasswordAuthentication getPasswordAuthentication() {
return auth;
}
}
...
HTTP プロキシと SOCKS プロキシは、ネットワーク スタック内の異なるレベルで動作するため、どちらか一方、または両方を使用できます。
これらのフラグは、次のようにプログラムで設定できます。
if (needsProxy()) {
System.setProperty("http.proxyHost",getProxyHost());
System.setProperty("http.proxyPort",getProxyPort());
} else {
System.setProperty("http.proxyHost","");
System.setProperty("http.proxyPort","");
}
メソッドから適切な値を返すだけでneedsProxy()
、いつでもこのコード スニペットを呼び出すことができます。getProxyHost()
getProxyPort()
JVM はプロキシを使用して HTTP 呼び出しを行います
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
これはユーザー設定プロキシを使用する場合があります
System.setProperty("java.net.useSystemProxies", "true");
プロキシ サーバーに関するいくつかのプロパティを jvm パラメータとして設定できます。
-Dhttp.proxyPort=8080、proxyHost など。
ただし、認証プロキシを通過する必要がある場合は、次の例のようなオーセンティケーターが必要です。
ProxyAuthenticator.java
import java.net.*;
import java.io.*;
public class ProxyAuthenticator extends Authenticator {
private String userName, password;
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password.toCharArray());
}
public ProxyAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
}
Example.java
import java.net.Authenticator;
import ProxyAuthenticator;
public class Example {
public static void main(String[] args) {
String username = System.getProperty("proxy.authentication.username");
String password = System.getProperty("proxy.authentication.password");
if (username != null && !username.equals("")) {
Authenticator.setDefault(new ProxyAuthenticator(username, password));
}
// here your JVM will be authenticated
}
}
java.net.useSystemProxies
プロパティを に設定しますtrue
。たとえば、JAVA_TOOL_OPTIONS環境変数を使用して設定できます。Ubuntu では、たとえば、次の行を に追加できます.bashrc
。
export JAVA_TOOL_OPTIONS+=" -Djava.net.useSystemProxies=true"
XML ファイルを読み取り、そのスキーマをダウンロードする必要がある
インターネット経由でスキーマまたは DTD を取得することを期待している場合、構築するアプリケーションは遅く、おしゃべりで、壊れやすいものです。ファイルをホストしているリモート サーバーに計画的または計画外のダウンタイムが発生するとどうなりますか? アプリが壊れます。それは大丈夫ですか?
http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.filesを参照してください。
スキーマなどの URL は、一意の識別子と考えるのが最適です。実際にそのファイルにリモートでアクセスする要求ではありません。「XMLカタログ」でGoogle検索を行います。XML カタログを使用すると、そのようなリソースをローカルでホストできるため、遅さ、おしゃべり、脆弱性を解決できます。
これは基本的に、リモート コンテンツの永続的にキャッシュされたコピーです。リモート コンテンツは変更されないため、これで問題ありません。更新がある場合は、別の URL になります。インターネットを介したリソースの実際の取得を特にばかげています。
私もファイアウォールの背後にいます。これは私にとってはうまくいきました!!
System.setProperty("http.proxyHost", "proxy host addr");
System.setProperty("http.proxyPort", "808");
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("domain\\user","password".toCharArray());
}
});
URL url = new URL("http://www.google.com/");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
// Read it ...
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
それは私のために働く:
public void setHttpProxy(boolean isNeedProxy) {
if (isNeedProxy) {
System.setProperty("http.proxyHost", getProxyHost());
System.setProperty("http.proxyPort", getProxyPort());
} else {
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
}
}
P/S: GHad の回答に基づいています。
最近、JVM がブラウザのプロキシ設定を使用できるようにする方法を発見しました。あなたがする必要があるのは${java.home}/lib/deploy.jar
、プロジェクトに追加し、次のようにライブラリを初期化することです:
import com.sun.deploy.net.proxy.DeployProxySelector;
import com.sun.deploy.services.PlatformType;
import com.sun.deploy.services.ServiceManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public abstract class ExtendedProxyManager {
private static final Log logger = LogFactory.getLog(ExtendedProxyManager.class);
/**
* After calling this method, proxy settings can be magically retrieved from default browser settings.
*/
public static boolean init() {
logger.debug("Init started");
// Initialization code was taken from com.sun.deploy.ClientContainer:
ServiceManager
.setService(System.getProperty("os.name").toLowerCase().indexOf("windows") != -1 ? PlatformType.STANDALONE_TIGER_WIN32
: PlatformType.STANDALONE_TIGER_UNIX);
try {
// This will call ProxySelector.setDefault():
DeployProxySelector.reset();
} catch (Throwable throwable) {
logger.error("Unable to initialize extended dynamic browser proxy settings support.", throwable);
return false;
}
return true;
}
}
その後、プロキシ設定は を介して Java API で使用できますjava.net.ProxySelector
。
このアプローチの唯一の問題はdeploy.jar
、bootclasspath でJVM を起動する必要があることですjava -Xbootclasspath/a:"%JAVA_HOME%\jre\lib\deploy.jar" -jar my.jar
。誰かがこの制限を克服する方法を知っているなら、私に知らせてください。
他の回答で指摘されているように、認証されたプロキシを使用する必要がある場合、純粋にコマンドライン変数を使用してこれを行う信頼できる方法はありません。これは、他の誰かのアプリケーションを使用していて、ソースコード。
Will Iversonは、Using HttpProxy to connect to host to host with preemtive authentication で、これを処理するために Proxifier (Mac OS X および Windows の場合はhttp://www.proxifier.com/ ) などのプロキシ管理ツールを使用するという有益な提案を行っています。
たとえば、Proxifier を使用すると、(認証された) プロキシを介して管理およびリダイレクトされる Java コマンドのみをインターセプトするように設定できます。ただし、この場合、proxyHost と proxyPort の値を空白に設定する必要があります。たとえば-Dhttp.proxyHost= -Dhttp.proxyPort=
、Java コマンドに渡します。
スタンドアロン JVM 内にいる場合は http.proxy* JVM 変数を利用できますが、起動スクリプトを変更したり、アプリケーション サーバー内でこれを行ったりしないでください (jboss または tomcat を除く)。代わりに、JAVA Proxy API (System.setProperty ではない) を使用するか、ベンダー独自の構成オプションを使用する必要があります。WebSphere と WebLogic はどちらも、J2SE よりもはるかに強力なプロキシの設定方法を明確に定義しています。さらに、WebSphere と WebLogic の場合、起動スクリプトをオーバーライドすることで、アプリケーション サーバーを少し壊してしまう可能性があります (特に、プロキシも使用するようにサーバーに指示している可能性があるため、サーバーの相互運用プロセス...)。
WINHTTPの設定も機能すると思います。
Windows Updateを含む多くのプログラムは、プロキシの背後で問題を抱えています。WINHTTPを設定することにより、この種の問題は常に修正されます