http://llying.iteye.com/blog/752735
httpclient4 取得cookie信息并保存
- HttpClient httpClient = new DefaultHttpClient();
- HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
- HttpHost httpHost = new HttpHost("localhost");
- HttpGet httpGet = new HttpGet("/https/");
- HttpResponse response = httpClient.execute(httpHost,httpGet);
- if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
- //请求成功
- //取得请求内容
- HttpEntity entity = response.getEntity();
- //显示内容
- if (entity != null) {
- // 显示结果
- System.out.println(EntityUtils.toString(entity,"utf-8"));
- }
- }
- //模拟写cookie
- httpGet = new HttpGet("/https/index.jsp?cookie=write");
- response = httpClient.execute(httpHost,httpGet);
- FileWriter fw = new FileWriter("C:/cookie.txt");
- //读取cookie并保存文件
- List<Cookie> cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
- if (cookies.isEmpty()) {
- System.out.println("None");
- } else {
- for (int i = 0; i < cookies.size(); i++) {
- System.out.println("- " + cookies.get(i).toString());
- fw.write(cookies.get(i).toString()+"\r\n");
- }
- }
- fw.close();
- if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
- //请求成功
- //取得请求内容
- HttpEntity entity = response.getEntity();
- //显示内容
- if (entity != null) {
- // 显示结果
- System.out.println(EntityUtils.toString(entity,"utf-8"));
- }
- }