2012-02-23 42 views
2

我想用javax.xml.transform.Transformer轉換XML文件,但我的Web訪問通過代理。使用Java XML Transformer和網絡代理

我試過在變壓器上使用一個新的URIResolver,但那不起作用。我如何指示變壓器使用代理?

回答

3

對於來自JDK的一般網絡訪問,一個選項是在啓動時傳遞JDK參數。

喜歡的東西:

java -Dhttp.proxyHost=myproxy.com -Dhttp.proxyPort=8080 ... MyTransformerClass 

往往是一個更好的解決方案是在編程應用程序中使用你從配置文件讀取值設置的選項。

喜歡的東西:

System.setProperty("http.proxyHost", myConfig.getProxyHost()); 
System.setProperty("http.proxyPort", myConfig.getProxyPort()); 

所有的選項見http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

然而,在你需要解決XSD XML處理的具體例子,DTD等,這幾乎總是最好有一個嘗試使用本地資源副本,並將javax.xml.stream.XMLResolver指定給解析器以加載本地副本而不是遠程。

+0

謝謝,正是我所需要的! – STM 2012-02-23 10:52:33

1

您需要在應用程序中設置代理。

首先,你需要創建一個擴展java.net.Authenticator像這樣的一類:

import java.net.Authenticator; 
import java.net.PasswordAuthentication; 

public class SimpleAuthenticator extends Authenticator { 

    private String username, password; 

    public SimpleAuthenticator(String username, String password) { 

     this.username = username; 
     this.password = password; 
    } 

    protected PasswordAuthentication getPasswordAuthentication() { 

     return new PasswordAuthentication(username, password.toCharArray()); 
    } 
} 

其次,在你的代碼初始化身份驗證:

SimpleAuthenticator sm = new simpleAuthenticator("user", "pass") 
Authenticator.setDefault(sm); 

三,通過港口,代理爲系統屬性到您的應用程序。隨着碼頭和maven它看起來像:

mvn jetty:run -DproxySet=true -DproxyHost=proxy.company.com -DproxyPort=8080