从response.header中提取cookie,在request里添加cookie

时间:2024-03-09 14:51:47

//        List<String> resp = new ArrayList<String>();  
//        HeaderIterator headers = response.headerIterator("Set-Cookie");
//      while(headers.hasNext()){
//        resp.add(headers.next().toString().replace("Set-Cookie: ", ""));
//    }

 


//                    headers=response.getAllHeaders();
//                for (Header header : headers) {
//                    System.out.println("CorpSubmit,header--- " + header.getName()
//                      + ": " + header.getValue());
//                }

 

 

 

cookiek另一种添加到request中的方式,会出现timeout错误

Map<String, Map<String, String>> cookies = null;
cookies = site.getAllCookies();//.getCookies();
HttpContext localContext = new BasicHttpContext();
getSiteCookies(localContext, cookies);
logger.info("localContext:::::"+cookies);
httpResponse = getHttpClient(site).execute(httpUriRequest, localContext);
cookieStore = ((AbstractHttpClient) getHttpClient(site)).getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie ck : cookies){
//site.addCookie(ck);
logger.info(ck.toString());
}

private void getSiteCookies(HttpContext localContext, Map<String, Map<String, String>> cookies){
CookieStore cookieStore = new BasicCookieStore();
for (Entry<String, Map<String, String>> entry : cookies.entrySet()) {
String domain=entry.getKey();
Map<String, String> cks= entry.getValue();
for (Map.Entry<String, String> v : cks.entrySet()) {
String name = v.getKey();
String value = v.getValue();
System.out.println("get from site::::::::::::"+ domain + ", " + name + ", " + value);
BasicClientCookie cookie = new BasicClientCookie(name, value);
cookie.setDomain(domain);
cookieStore.addCookie(cookie);
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
break;
}

}