문제

많은 시간은,자바 응용 프로그램을 필요가 인터넷에 연결합니다.가장 일반적인 예이 발생할 때 XML 파일을 읽을 필요로 스키마.

나는 프록시 서버 뒤에.는 방법을 설정할 수 있습니까 JVM 을 프록시를 사용할 수?

도움이 되었습니까?

해결책

에서 Java 설명서( javadoc API):

http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

Set the JVM 플래그 http.proxyHosthttp.proxyPort 시작할 때 JVM 에서는 명령줄입니다.이것은 일반적으로 수행 쉘 스크립트에서(유닉스)또는 bat 파일(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 및/또는 양말 프록시를 프로그래밍 방식으로 설정하려면 :

...

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 프록시 및 양말 프록시는 네트워크 스택에서 다른 레벨에서 작동하므로 하나 또는 다른 하나 또는 둘 다를 사용할 수 있습니다.

이런 식으로 그 플래그를 프로그래밍 방식으로 설정할 수 있습니다.

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;
    }
}

예. 자바

    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

    }
}

이 답변에 따라 :http://mail-archives.apache.org/mod_mbox/jakarta-jmeter-user/200208.mbox/%3c494fd350388ad511a9dd002530f33102f1dc2c@mmsx006%3E

분류기와 Javabrett/Leonel의 답변 결합 :

java -Dhttp.proxyHost=10.10.10.10 -Dhttp.proxyPort=8080 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password -jar myJar.jar

XML 파일을 읽고 스키마를 다운로드해야합니다.

인터넷을 통해 스키마 또는 DTD를 검색하는 데 의존하는 경우 느리고 수다스럽고 깨지기 쉬운 응용 프로그램을 구축합니다. 파일을 호스팅하는 원격 서버가 계획되거나 계획되지 않은 가동 중지 시간을 차지하면 어떻게됩니까? 앱이 끊어집니다. 그 확인은?

보다 http://xml.apache.org/commons/components/resolver/resolver-article.html#s.catalog.files

URL은 Schemas 등을위한 것 등은 고유 식별자로 가장 잘 생각됩니다. 실제로 해당 파일에 원격으로 액세스하는 요청이 아닙니다. "XML 카탈로그"에서 Google 검색을 수행하십시오. XML 카탈로그를 사용하면 그러한 리소스를 로컬로 호스팅하여 속도가 느려지고 차트와 취약성을 해결할 수 있습니다.

기본적으로 원격 콘텐츠의 영구적으로 캐시 된 사본입니다. 그리고 원격 콘텐츠는 결코 변하지 않기 때문에 괜찮습니다. 업데이트가 있다면 다른 URL에있을 것입니다. 인터넷을 통해 자원의 실제 검색을 특히 어리석게 만듭니다.

설정 java.net.useSystemProxies 속성 true. 예를 들어, java_tool_options 환경 변수. 예를 들어 Ubuntu에서는 다음 줄을 추가 할 수 있습니다. .bashrc:

내보내기 java_tool_options+= "-djava.net.usesystemproxies = true"

나는 또한 방화벽 뒤에 있습니다. 이것은 나를 위해 일했습니다 !!

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();

다음은 Java를 대리로 설정하는 방법을 보여줍니다. 프록시 사용자 및 프록시 비밀번호 명령 줄에서 매우 일반적인 경우입니다. 코드에 비밀번호와 호스트를 저장해서는 안됩니다.

시스템 속성을 명령으로 -d로 전달하고 System.setProperty ( "name", "value")를 사용하여 코드로 설정하는 것은 동일합니다.

그러나 이것에 주목하십시오

작동하는 예 :

C:\temp>java -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps=proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit com.andreas.JavaNetHttpConnection

그러나 다음은 다음과 같습니다 작동하지 않습니다

C:\temp>java com.andreas.JavaNetHttpConnection -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps=proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit

유일한 차이점은 시스템 속성의 위치입니다! (수업 전후)

비밀번호에 특수 문자가있는 경우 위의 예에서와 같이 "@mypass123%"인용문에 넣을 수 있습니다.

HTTPS 서비스에 액세스하는 경우 https.proxyhost, https.proxyport 등을 사용해야합니다.

HTTP 서비스에 액세스하는 경우 http.proxyhost, http.proxyport 등을 사용해야합니다.

프록시 뒤의 URL에 연결하기 전에 이것을 추가하십시오.

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");

이것은 사소한 업데이트이지만 Java 7이므로 프록시 연결은 이제 시스템 속성을 통해서보다는 프로그래밍 방식으로 생성 될 수 있습니다. 이것은 다음과 같은 경우에 유용 할 수 있습니다.

  1. 프로그램의 런타임 중에 프록시가 동적으로 회전해야합니다.
  2. 여러 병렬 프록시를 사용해야합니다
  3. 또는 코드를 더 깨끗하게 만드십시오 :)

Groovy의 고안된 예는 다음과 같습니다.

// proxy configuration read from file resource under "proxyFileName"
String proxyFileName = "proxy.txt"
String proxyPort = "1234"
String url = "http://www.promised.land"
File testProxyFile = new File(proxyFileName)
URLConnection connection

if (!testProxyFile.exists()) {

    logger.debug "proxyFileName doesn't exist.  Bypassing connection via proxy."
    connection = url.toURL().openConnection()

} else {
    String proxyAddress = testProxyFile.text
    connection = url.toURL().openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)))
}

try {
    connection.connect()
}
catch (Exception e) {
    logger.error e.printStackTrace()
}

전체 참조 :http://docs.oracle.com/javase/7/docs/technotes/guides/net/proxies.html

"Socks Proxy"를 원한다면 "SocksproxyHost"및 "Socksproxyport"VM 인수를 알리십시오.

예를 들어

java -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=8080 org.example.Main

최근에 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.

이 접근법의 유일한 문제는 JVM을 deploy.jar BootClassPath 예 : java -Xbootclasspath/a:"%JAVA_HOME%\jre\lib\deploy.jar" -jar my.jar. 누군가이 한계를 극복하는 방법을 알고 있다면 알려주세요.

그것은 나를 위해 작동합니다 :

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의 답변을 기반으로합니다.

다른 답변에서 지적 된 바와 같이, 인증 된 프록시를 사용해야한다면, 명령 줄 변수를 순전히 사용하는 신뢰할 수있는 방법은 없다. 소스 코드.

윌 아이버슨 도움이되는 제안을합니다 httpproxy를 사용하여 전제 인증이있는 호스트에 연결 Proxifier와 같은 프록시 관리 도구를 사용하려면 ( http://www.proxifier.com/ Mac OS X 및 Windows)를 처리합니다.

예를 들어, 프록시퍼를 사용하면 (인증 된) 프록시를 통해 관리 및 리디렉션 할 Java 명령 만 인터셉트 할 수 있습니다. 이 경우 프록시 호스트 및 프록시 포트 값을 공백으로 설정하고 싶을 것입니다. -Dhttp.proxyHost= -Dhttp.proxyPort= Java 명령에.

또한 항상 동일한 스키마를 다운로드하려는 경우 클래스 경로 (파일 시스템 또는 JAR)에 스키마를 추가 한 다음 사용자 정의를 사용할 수 있습니다. EntityResolver

보다 여기 이 접근법에 대한보다 완전한 논의를 위해.

편집 : 참조 @me.yahoo.com/a/0qmxe 's EntityResolver 접근법을 사용하는 Catalogresolver에 대한 토론 :

CatalogResolver cr = new CatalogResolver();
...
yourParser.setEntityResolver(cr) 

독립형 JVM 내에있는 경우 http.proxy* JVM 변수를 활용할 수 있지만 시작 스크립트를 수정하거나 응용 프로그램 서버 내에서이를 수행하지 않아야합니다 (JBoss 또는 Tomcat 제외). 대신 Java Proxy API (System.SetProperty 아님)를 사용하거나 공급 업체의 자체 구성 옵션을 사용해야합니다. WebSphere와 Weblogic은 모두 J2SE보다 훨씬 강력한 프록시를 설정하는 매우 정의 된 방법을 가지고 있습니다. 또한 WebSphere 및 Weblogic의 경우 시작 스크립트 (특히 프록시를 사용하도록 지시 할 수있는 서버의 인터 로프 프로세스 ...)를 재정의하여 애플리케이션 서버를 거의 방법으로 분해 할 수 있습니다.

나는 구성한다고 생각합니다 winhttp 또한 작동합니다.

Windows 업데이트를 포함한 많은 프로그램은 프록시 뒤에 문제가 있습니다. Winhttp를 설정하면 항상 이런 종류의 문제가 해결됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top