您的位置:首页 > 理论基础 > 计算机网络

读取httpCookie并写入文件

2014-11-27 16:30 387 查看
package citi.icy1127;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URI;
import java.net.URL;
import java.nio.CharBuffer;
import java.text.SimpleDateFormat;
import java.util.List;

public class CookieRead {
public static void main(String []args){
String urlStr="http://www.google.com";
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
try {
URL url=new URL(urlStr);
CookieManager mana=new CookieManager();
mana.setCookiePolicy(new MyCookiePolicy());
CookieHandler.setDefault(mana);
List<HttpCookie> cookies=mana.getCookieStore().getCookies();
//设置好cookie之后再建立链接
Object obj=url.openConnection(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("代理地址",代理端口号))).getContent();//不使用代理时参数为空

FileWriter fw=new FileWriter(new File("cookie.txt"));
for(HttpCookie hc:cookies){
fw.write("\r\n----------------------------------------- ----------------------\r\n");
fw.write("cookie name\t"+hc.getName()+"\r\n");
fw.write("cookie Domain\t"+hc.getDomain()+"\r\n");
long age=hc.getMaxAge();
if(age!=-1)//-1不能被格式化??
fw.write("cookie age\t"+sdf.format(age)+"\r\n");
else{
fw.write("the cookie will expired when browser closes\r\n");
}
fw.write("cookie value\t"+hc.getValue()+"\r\n");
fw.flush();
}
FileReader fr=new FileReader("cookie.txt");
BufferedReader bf=new BufferedReader(fr);
String str="";
while((str=bf.readLine()) != null){
System.out.println(str);
}

for(HttpCookie hc:cookies){
System.out.println("name "+hc.getName());
System.out.println("Domain "+hc.getDomain());
long age=hc.getMaxAge();
if(age==-1){
System.out.println("the cookie will expired when browser closes");

}else{
System.out.printf("this cookie will expired in %s seconds %n",sdf.format(age));
}
System.out.println("secured:"+ ((Boolean)hc.getSecure()).toString());
System.out.println("value: "+hc.getValue()+"\n");

}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-gen
System.out.println("bug bug bug bug");
}
System.out.println("no bug no bug no bug no bug");
}

}
class MyCookiePolicy implements CookiePolicy{

@Override
public boolean shouldAccept(URI arg0, HttpCookie arg1) {
// TODO Auto-generated method stub
return true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: