java.net.httpurlconnection 包_java.net.HttpURLConnection的使用

web登陆无非就是网页获取,cookie 的管理,post和get方式的模拟。

1.网页内容获取

java.io.inputstream in;

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

java.net.httpurlconnection connection = (java.net.httpurlconnection)

url.openconnection();

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

//模拟成ie

connection.setrequestproperty("user-agent","mozilla/4.0 (compatible; msie 6.0; windows 2000)");

connection.connect();

in = connection.getinputstream();

java.io.bufferedreader breader =

new bufferedreader(new inputstreamreader(in , "gbk"));

string str=breader.readline());

while(st != null){

system.out.println(str);

str=breader.readline());

}

2.cookie管理

1.直接的方式

取得cookie:

httpurlconnection huc= (httpurlconnection) url.openconnection();

inputstream is = huc.getinputstream();

// 取得sessionid.

string cookieval = hc.getheaderfield("set-cookie");

string sessionid;

if(cookieval != null)

{

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

}

发送设置cookie:

httpurlconnection huc= (httpurlconnection) url.openconnection();

if(sessionid != null)

{

huc.setrequestproperty("cookie", sessionid);

}

inputstream is = huc.getinputstream();

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

获取cookie:

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

httpurlconnection huc = (httpurlconnection) url.openconnection();

huc.connect();

inputstream is = huc.getinputstream();

client client = new client();

cookiejar cj = client.getcookies(huc);

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

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

huc = (httpurlconnection) url.openconnection();

client.setcookies(huc, cj);

3.post方式的模拟

url url = new url("www.xyz.com");

httpurlconnection huc = (httpurlconnection) url.openconnection();

//设置允许output

huc.setdooutput(true);

//设置为post方式

huc.setrequestmethod("post");

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

stringbuffer sb = new stringbuffer();

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

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

//post信息

outputstream os = huc.getoutputstream();

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

os.close();

bufferedreader br = new bufferedreader(new inputstreamreader(huc.getinputstream()))

huc.connect();

string line = br.readline();

while(line != null){

l

system.out.printli(line);

line = br.readline();

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值