日期:2014-05-20  浏览次数:21021 次

HttpClient如何设置代理服务器访问外网?
描述:
在java程序里访问外网。服务器是代理的。
之前用Jsoup.connect(LOGIN_URL)的方法,也是访问不了外网,听CSDN大神们的建议,追加了
static {
 System.getProperties().setProperty("proxySet", "true");
 System.getProperties().setProperty("http.proxyHost", "代理IP");
 System.getProperties().setProperty("http.proxyPort", "8080");
 }code]
就可以访问了,但是我现在想用httpclient来传数据,像这样
[code=java]HttpClient client = new HttpClient();client.executeMethod(post)

总是报如下错误:
10 04, 2013 10:27:27 午前 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
情報: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
10 04, 2013 10:27:27 午前 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
情報: Retrying request
HttpClient? 代理服务器

------解决方案--------------------
超时时间再设置一下,网络不好也会造成这样的问题:

System.getProperties().setProperty("proxySet", "true");
         System.getProperties().setProperty("http.proxyHost", "代理IP");
         System.getProperties().setProperty("http.proxyPort", "8080");

Connection conn = Jsoup.connect(url);
conn.timeout(20000);
Document doc = conn.get();

------解决方案--------------------
换成这种
HttpClient httpClient = new HttpClient();  
httpClient.getHostConfiguration().setProxy("xxx", 8080);  
//httpClient.getParams().setAuthenticationPreemptive(true);  
//httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials("xxxx","xxxx"));
        //使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https
        HttpMethod method = new GetMethod("http://java.sun.com/");

------解决方案--------------------
 httpClient.getHostConfiguration().setProxy("xxx", 8080);  这种方式可以我测试过了。
需要用户名密码的话就用。不需要就 不用。


------解决方案--------------------
测试过可以
public static void main(String[] args) throws Exception
    {   
HttpClient httpClient = new HttpClient();  
httpClient.getHostConfiguration().setProxy("xxxx", 8080);  
        HttpMethod method = new GetMethod("http://java.sun.com/");

        httpClient.executeMethod(method);
        InputStream  in = method.getResponseBodyAsStream(); 
        File file = new File("D:/b.html");  
        OutputStream os = new FileOutputStream(file);  
        byte[] buff = new byte[4096];  
        int len=-1;  
        while((len=in.read(buff))!=-1){  
            os.write(buff,0,len);  
        }  
        in.close();  
        os.close();  
        method.releaseConnection();
    }