这篇文章主要讲解 httpclient如何使用cookie
我们在使用httpclient模拟登陆时,要保留登陆时服务器返回的cookie,这时我们要使用BasicCookieStore
maven 配置
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.3</version> </dependency>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| package org.xxz.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; 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.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /* commons-logging-1.2.jar httpclient-4.5.3.jar httpcore-4.4.3.jar httpmime-4.5.3.jar */ public class HttpUtil { private static BasicCookieStore cookieStore = new BasicCookieStore(); // 设置请求超时时间 private static RequestConfig config = RequestConfig.custom()// .setSocketTimeout(5000) // .setConnectTimeout(5000) // .setConnectionRequestTimeout(5000) // .build(); public static String post(String url, Map<String, String> params) { HttpPost request = new HttpPost(url); request.setConfig(config); buildParams(params, request); return req(request); } private static void buildParams(Map<String, String> params, HttpPost request) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (params != null && params.size() > 0) { for (Map.Entry<String, String> entry : params.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try { request.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("无效的字符编码", e); } } } private static String req(HttpUriRequest request) { CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); System.out.println("status=" + status); HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } }; String responseBody = null; try { responseBody = httpClient.execute(request, responseHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("-------" + request.getURI() + "-------"); System.out.println("responseBody=" + responseBody); printCookie(); return responseBody; } private static void printCookie() { System.out.print("cookies="); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.print(cookies.get(i).toString()); } System.out.println("\n------------------------------------------"); } } }
|
如果您觉得文章有用或对您有帮助,欢迎通过以下方式赞助我。 ♪(^∀^●)ノ