2017-07-31 78 views
2

我正嘗試通過代理服務器訪問網站。我正在使用httpclient。動態獲取代理服務器詳細信息時SOCKS服務器的格式錯誤

這是工作正常的代碼:

import org.apache.commons.httpclient.Credentials; 
import org.apache.commons.httpclient.HostConfiguration; 
import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.HttpMethod; 
import org.apache.commons.httpclient.HttpStatus; 
import org.apache.commons.httpclient.UsernamePasswordCredentials; 
import org.apache.commons.httpclient.auth.AuthScope; 
import org.apache.commons.httpclient.methods.GetMethod; 
import java.io.IOException; 
import java.net.InetSocketAddress; 
import java.net.Proxy; 
import java.net.ProxySelector; 
import java.net.URI; 
import java.net.URISyntaxException; 
import java.util.Properties; 

public class Working { 
private static String PROXY_HOST = "proxy.test.org"; 
private static int PROXY_PORT = 80; 

    public static void main(String[] args) { 
    HttpClient client = new HttpClient(); 
    HttpMethod method = new GetMethod("https://www.example.org"); 
    HostConfiguration config = client.getHostConfiguration(); 
    config.setProxy(PROXY_HOST, PROXY_PORT); 

    try { 
      client.executeMethod(method); 
      if (method.getStatusCode() == HttpStatus.SC_OK) { 
      String response = method.getResponseBodyAsString(); 
      System.out.println("Response = " + response); 
         } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     method.releaseConnection(); 
    } 
    System.out.println("end"); 
    } 
} 

但是當我使用下面的方法來設置proxy_host使用和proxy_port使用值動態我正在「從SOCKS服務器畸形的答覆」異常

public static void getProxyDetails() 
{ 
    Properties systemSettings = System.getProperties(); 
    systemSettings.put("proxySet", "true"); 
    try { 
     Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI(
       "https://www.example2.com/xyz")).iterator(). 
      next(); 
     System.out.println("proxy hostname : " + proxy.type()); 
      InetSocketAddress addr = (InetSocketAddress)proxy.address(); 
      if (addr == null) { 
       System.out.println("No Proxy"); 
      } else { 
       System.out.println("proxy hostname : " + addr.getHostName()); 
       System.out.println("proxy port : " + addr.getPort()); 
       PROXY_HOST = addr.getHostName(); 
       PROXY_PORT = addr.getPort();    
      } 
    } catch (URISyntaxException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

我嘗試了本網站提供的其他建議,但沒有解決我的問題。 我在代碼中犯了什麼錯誤?任何幫助表示讚賞。

回答

相關問題