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

java.net.HttpURLConnection的使用

2008-07-03 16:19 645 查看
web登陆无非就是网页获取,cookie的管理,post和get方式的模拟。

1.网页内容获取

java.io.inputstreamin;

java.net.urlurl=newjava.net.url(www.xyz.com/content.html);

java.net.httpurlconnectionconnection=(java.net.httpurlconnection)

url.openconnection();

connection=(java.net.httpurlconnection)url.openconnection();

//模拟成ie

connection.setrequestproperty("user-agent","mozilla/4.0(compatible;msie6.0;windows2000)");

connection.connect();

in=connection.getinputstream();

java.io.bufferedreaderbreader=

newbufferedreader(newinputstreamreader(in,"gbk"));

stringstr=breader.readline());

while(st!=null){

system.out.println(str);

str=breader.readline());

}

2.cookie管理

1.直接的方式

取得cookie:

httpurlconnectionhuc=(httpurlconnection)url.openconnection();

inputstreamis=huc.getinputstream();

//取得sessionid.

stringcookieval=hc.getheaderfield("set-cookie");

stringsessionid;

if(cookieval!=null)

{

sessionid=cookieval.substring(0,cookieval.indexof(";"));

}

发送设置cookie:

httpurlconnectionhuc=(httpurlconnection)url.openconnection();

if(sessionid!=null)

{

huc.setrequestproperty("cookie",sessionid);

}

inputstreamis=huc.getinputstream();

2.利用的jcookie包(http://jcookie.sourceforge.net/)

获取cookie:

urlurl=newurl("http://www.site.com/");

httpurlconnectionhuc=(httpurlconnection)url.openconnection();

huc.connect();

inputstreamis=huc.getinputstream();

clientclient=newclient();

cookiejarcj=client.getcookies(huc);

新的请求,利用上面获取的cookie:

url=newurl("http://www.site.com/");

huc=(httpurlconnection)url.openconnection();

client.setcookies(huc,cj);

3.post方式的模拟

urlurl=newurl("www.xyz.com");

httpurlconnectionhuc=(httpurlconnection)url.openconnection();

//设置允许output

huc.setdooutput(true);

//设置为post方式

huc.setrequestmethod("post");

huc.setrequestproperty("user-agent","mozilla/4.7[en](win98;i)");

stringbuffersb=newstringbuffer();

sb.append("username="+usernme);

sb.append("&password="+password);

//post信息

outputstreamos=huc.getoutputstream();

os.write(sb.tostring().getbytes("gbk"));

os.close();

bufferedreaderbr=newbufferedreader(newinputstreamreader(huc.getinputstream()))

huc.connect();

stringline=br.readline();

while(line!=null){

l

system.out.printli(line);

line=br.readline();

}


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