【问题标题】:Use Java XML Transformer with a network proxy将 Java XML Transformer 与网络代理一起使用
【发布时间】:2012-03-13 17:44:00
【问题描述】:

我想用javax.xml.transform.Transformer 转换一个 XML 文件,但我的 Web 访问要通过代理。

我尝试使用新的URIResolver 和变压器,但没有奏效。如何指示转换器使用代理?

【问题讨论】:

    标签: java xml networking transform


    【解决方案1】:

    对于从 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了解所有选项

    但是,在 XML 处理的具体示例中,您需要解析 XSD、DTD 等。您尝试过拥有资源的本地副本并指定 javax.xml.stream.XMLResolver 几乎总是更好您的解析器加载本地副本而不是远程。

    【讨论】:

      【解决方案2】:

      您需要在应用程序中设置代理。

      首先,您需要创建一个扩展 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());
          }
      }
      

      其次,在你的代码中初始化Authenticator:

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

      第三,将端口、代理作为系统属性传递给您的应用程序。使用 jetty 和 maven,它看起来像:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-10
        • 1970-01-01
        • 2013-01-10
        • 2018-11-02
        • 2014-03-06
        • 2016-12-09
        相关资源
        最近更新 更多