2012-05-02 138 views
12

嗨我有一個球衣客戶端,我用它來上傳文件。我嘗試在本地使用它,一切正常。但在生產環境中,我必須設置代理。我瀏覽了幾頁,但無法得到確切的解決方案。有人可以幫助我嗎?澤西客戶端+設置代理

這裏是我的客戶端代碼:

File file = new File("e:\\test.zip"); 
FormDataMultiPart part = new FormDataMultiPart(); 

    part.bodyPart(new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); 

    WebResource resource = null; 

    if(proxy.equals("yes")){ 
    //How do i configure client in this case? 

    }else{ 
      //this uses system proxy i guess 
     resource = Client.create().resource(url); 
    } 

    String response = (String)resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class, part); 

    System.out.println(response); 

回答

2

在這裏你去:

DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); 
     config.getProperties().put(
     ApacheHttpClient4Config.PROPERTY_PROXY_URI, 
     "PROXY_URL" 
); 

config.getProperties().put(
     ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME, 
     "PROXY_USER" 
); 

config.getProperties().put(
     ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD, 
     "PROXY_PASS" 
);  

Client c = ApacheHttpClient4.create(config); 
WebResource r = c.resource("https://www.google.com/"); 
12

還有一個更簡單的方法,如果你想避免在傳統項目更多的圖書館,也沒有必要代理驗證:

首先你需要一個實現的類HttpURLConnectionFactory

import java.io.IOException; 
import java.net.HttpURLConnection; 
import java.net.InetSocketAddress; 
import java.net.Proxy; 
import java.net.URL; 

import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory; 


public class ConnectionFactory implements HttpURLConnectionFactory { 

    Proxy proxy; 

    private void initializeProxy() { 
     proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy.com", 3128)); 
    } 

    public HttpURLConnection getHttpURLConnection(URL url) throws IOException { 
     initializeProxy(); 
     return (HttpURLConnection) url.openConnection(proxy); 
    } 
} 

二是實例化一個com.sun.jersey.client.urlconnection.URLConnectionHandler

URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory()); 

,三是使用Client構造函數,而不是Client.create

Client client = new Client(ch); 

當然你也可以自定義代理服務器的初始化在ConnectionFactory

+1

它爲我工作.......... –

9

luckyluke答案應該工作。 這裏我的版本:

ClientConfig config = new DefaultClientConfig(); 
Client client = new Client(new URLConnectionClientHandler(
     new HttpURLConnectionFactory() { 
    Proxy p = null; 
    @Override 
    public HttpURLConnection getHttpURLConnection(URL url) 
      throws IOException { 
     if (p == null) { 
      if (System.getProperties().containsKey("http.proxyHost")) { 
       p = new Proxy(Proxy.Type.HTTP, 
         new InetSocketAddress(
         System.getProperty("http.proxyHost"), 
         Integer.getInteger("http.proxyPort", 80))); 
      } else { 
       p = Proxy.NO_PROXY; 
      } 
     } 
     return (HttpURLConnection) url.openConnection(p); 
    } 
}), config); 
0

我把user67871,改變了它一下。這種方法的好處在於它可以與Windows上的系統代理一起使用。如果你在Windows上,並且你在IE中配置了一個代理,那麼這段代碼將會選擇它。當您運行Fiddler時,它也會設置系統代理,這樣可以很容易地將Jersey和Fiddler一起使用。

Client client = new Client(new URLConnectionClientHandler(
      new HttpURLConnectionFactory() { 
     Proxy p = null; 

     @Override 
     public HttpURLConnection getHttpURLConnection(URL url) 
       throws IOException { 
      try { 
       if (p == null) { 
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI()); 
        if (proxies != null) { 
         // just use the first one, I don't know if we should sometimes use a different one 
         p = proxies.get(0); 
        } 
        if (p == null) { 
         p = Proxy.NO_PROXY; 
        } 
       } 
       return (HttpURLConnection) url.openConnection(p); 
      } catch (URISyntaxException ex) { 
       throw new IOException(ex); 
      } 
     } 
    }), config); 
0

首先,我創建了這個類

import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory; 
    import java.io.IOException; 
    import java.net.HttpURLConnection; 
    import java.net.InetSocketAddress; 
    import java.net.Proxy; 
    import java.net.URL; 
    import java.security.KeyManagementException; 
import java.security.NoSuchAlgorithmException; 
import java.security.SecureRandom; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.net.ssl.HostnameVerifier; 
import javax.net.ssl.HttpsURLConnection; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.TrustManager; 

/** 
* 
* @author Aimable 
*/ 
public class ConnectionFactory implements HttpURLConnectionFactory { 

    Proxy proxy; 

    String proxyHost; 

    Integer proxyPort; 

    SSLContext sslContext; 

    public ConnectionFactory() { 
    } 

    public ConnectionFactory(String proxyHost, Integer proxyPort) { 
     this.proxyHost = proxyHost; 
     this.proxyPort = proxyPort; 
    } 

    private void initializeProxy() { 
     proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); 
    } 

    @Override 
    public HttpURLConnection getHttpURLConnection(URL url) throws IOException { 
     initializeProxy(); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(proxy); 
     if (con instanceof HttpsURLConnection) { 
      System.out.println("The valus is...."); 
      HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection(proxy); 
      httpsCon.setHostnameVerifier(getHostnameVerifier()); 
      httpsCon.setSSLSocketFactory(getSslContext().getSocketFactory()); 
      return httpsCon; 
     } else { 
      return con; 
     } 

    } 

    public SSLContext getSslContext() { 
     try { 
      sslContext = SSLContext.getInstance("SSL"); 
      sslContext.init(null, new TrustManager[]{new SecureTrustManager()}, new SecureRandom()); 
     } catch (NoSuchAlgorithmException ex) { 
      Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (KeyManagementException ex) { 
      Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     return sslContext; 
    } 

    private HostnameVerifier getHostnameVerifier() { 
     return new HostnameVerifier() { 
      @Override 
      public boolean verify(String hostname, 
        javax.net.ssl.SSLSession sslSession) { 
       return true; 
      } 
     }; 
    } 

} 

然後我還創建名爲SecureTrustManager

import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 
import javax.net.ssl.X509TrustManager; 

/** 
* 
* @author Aimable 
*/ 
public class SecureTrustManager implements X509TrustManager { 

    @Override 
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) 
      throws CertificateException { 
    } 

    @Override 
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) 
      throws CertificateException { 
    } 

    @Override 
    public X509Certificate[] getAcceptedIssuers() { 
     return new X509Certificate[0]; 
    } 

    public boolean isClientTrusted(X509Certificate[] arg0) { 
     return true; 
    } 

    public boolean isServerTrusted(X509Certificate[] arg0) { 
     return true; 
    } 

} 

另一個類,然後創建該類我打電話給客戶這樣

URLConnectionClientHandler cc = new URLConnectionClientHandler(new ConnectionFactory(webProxy.getWebserviceProxyHost(), webProxy.getWebserviceProxyPort())); 
    client = new Client(cc); 
    client.setConnectTimeout(2000000); 

通過proxyHost替換webProxy.getWeserviceHost,並通過代理端口替換webProxy.getWebserviceProxyPort()。

這對我有效,它應該也適合你。請注意,我正在使用Jersey 1.8,但它也應該用於澤西島2

2
System.setProperty("http.proxyHost","your proxy url"); 
System.setProperty("http.proxyPort", "your proxy port"); 
0

SDolgy。我做了這個在Jersey客戶端實例化中添加3個功能: 啓用SSL TLSv1.1(需要JVM> = 1.7),配置conex。池。增加連接,設置系統代理。

# My props file  
# CONFIGURAR EL CLIENTE 
#PROXY_URI=http://5.5.5.5:8080 
#SECURITY_PROTOCOL=TLSv1.2 
#POOLING_HTTP_CLIENT_CONNECTION_MANAGER.MAXTOTAL=200 
#POOLING_HTTP_CLIENT_CONNECTION_MANAGER.DEFAULTMAXPERROUTE=20 

import java.util.Properties; 
import javax.net.ssl.SSLContext; 
import javax.ws.rs.client.Client; 
import javax.ws.rs.client.ClientBuilder; 

import org.apache.http.config.Registry; 
import org.apache.http.config.RegistryBuilder; 
import org.apache.http.conn.socket.ConnectionSocketFactory; 
import org.apache.http.conn.socket.PlainConnectionSocketFactory; 
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 

import org.glassfish.jersey.SslConfigurator; 
import org.glassfish.jersey.apache.connector.ApacheClientProperties; 
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; 
import org.glassfish.jersey.client.ClientConfig; 
import org.glassfish.jersey.client.ClientProperties; 
import org.glassfish.jersey.jackson.JacksonFeature; 

public class JerseyClientHelper { 
    private static Client cliente; 
    private static final Properties configuracion = SForceConfiguration.getInstance(); 

    public static synchronized Client getInstance() { 
     if (cliente == null) {    
      SSLContext sslContext = SslConfigurator.newInstance().securityProtocol(configuracion.getProperty("SECURITY_PROTOCOL")).createSSLContext(); // Usar TLSv1.2 

      SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext); 
      Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() 
      .register("http", PlainConnectionSocketFactory.getSocketFactory()) 
      .register("https", socketFactory) 
      .build(); 

      // Para configurar las conexiones simultaneas al servidor 
      int maxTotal = Integer.parseInt(configuracion.getProperty("POOLING_HTTP_CLIENT_CONNECTION_MANAGER.MAXTOTAL")); 
      int defaultMaxPerRoute = Integer.parseInt(configuracion.getProperty("POOLING_HTTP_CLIENT_CONNECTION_MANAGER.DEFAULTMAXPERROUTE")); 
      PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); 
      connectionManager.setMaxTotal(maxTotal); 
      connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); 

      ClientConfig config = new ClientConfig(); 
      config.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager); 
      config.connectorProvider(new ApacheConnectorProvider()); 
      config.property(ClientProperties.PROXY_URI, configuracion.getProperty("PROXY_URI")); // Debemos poner el PROXY del sistema 


      cliente = ClientBuilder.newBuilder().sslContext(sslContext).withConfig(config).build(); 

     }   
     return cliente; 
    } 

} 
相關問題