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 executeWithRetryHttpClient? 代理服务器
情報: 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
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/");
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();
}