在动态获取代理服务器详细信息时,SOCKS服务器的格式错误回复

时间:2017-07-31 13:45:49

标签: proxy socks apache-commons-httpclient proxy-server

我正在尝试通过代理服务器访问网站。我正在使用httpclient。

这是正常运行的代码:

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

我尝试了本网站提供的其他建议,但它没有解决我的问题。 我在代码中犯了什么错误吗?。感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

没关系。我能够通过使用HttpURLConnection而不是HttpClient来解决问题。 https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html