HttpClient设置代理,超时,以及得到cookies

import java.net.URI;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; public class Http { // 如何通过一个代理发送一个HTTP请求。
public void action1() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpHost target = new HttpHost("ip1", 8080, "https");
HttpHost proxy = new HttpHost("ip2", 8080, "http"); RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet request = new HttpGet("/");
request.setConfig(config); System.out.println("Executing request " + request.getRequestLine()
+ " to " + target + " via " + proxy); httpclient.execute(target, request);
} finally {
httpclient.close();
}
} // 得到cookies。
public void action2() throws Exception {
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore).build();
try {
// HttpGet httpget = new HttpGet("https://someportal/?username=username&password=password");
// CloseableHttpResponse response = httpclient.execute(httpget);
HttpUriRequest login = RequestBuilder.post()
.setUri(new URI("https://www.baidu.com/"))
.addParameter("username", "username")
.addParameter("password", "password").build();
httpclient.execute(login); System.out.println("请求所得的 cookies:");
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
} } finally {
httpclient.close();
} }
// 设置超时。
public void action3() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(1000)
.setConnectTimeout(1000)
.build();
HttpGet httpget1 = new HttpGet("https://www.baidu.com");
httpget1.setConfig(requestConfig);
httpclient.execute(httpget1);
}
}
上一篇:android httpclient 设置超时


下一篇:转 HttpClient 设置连接超时时间