`

httpclient4 取得cookie信息并保存

阅读更多
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"));
			}
		}
分享到:
评论
1 楼 szlwm 2011-07-10  
请问这样写Cookie,在服务器端的ServletRequest能读取到吗?

相关推荐

Global site tag (gtag.js) - Google Analytics