【Java】javanetHttpURLConnection的使用.doc
上传人:sy****28 上传时间:2024-09-14 格式:DOC 页数:3 大小:25KB 金币:16 举报 版权申诉
预览加载中,请您耐心等待几秒...

【Java】javanetHttpURLConnection的使用.doc

【Java】javanetHttpURLConnection的使用.doc

预览

在线预览结束,喜欢就下载吧,查找使用更方便

16 金币

下载此文档

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

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();//模拟成ieconnection.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();//设置允许outputhuc.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){lsystem.out.printli(line);