Java模拟Web登陆(Post模式)



			// 连接地址(通过阅读html源代码获得,即为登陆表单提交的URL)  
			String surl = "http://192.168.5.40:8090/ylysystem/systemmgmt/mainmanage/login.sc";  
			
			/** 
			* 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如: // Using 
			* java.net.URL and //java.net.URLConnection 
			*/  
			URL url = new URL(surl);  
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
			
			/** 
			* 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。 
			* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做: 
			*/  
			connection.setDoOutput(true);  //打开输出,向服务器输出参数(POST方式、字节)(写参数之前应先将参数的字节长度设置到配置"Content-Length"<字节长度>)
			connection.setDoInput(true);//打开输入,从服务器读取返回数据
			connection.setRequestMethod("POST"); //设置登录模式为POST(字符串大写)
			connection.setInstanceFollowRedirects(false); 
			connection.connect();
			/** 
			* 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ... 
			*/  
			OutputStreamWriter out = new OutputStreamWriter(connection  
			      .getOutputStream(), "utf-8");  
			//其中的loginName和loginPassword也是阅读html代码得知的,即为表单中对应的参数名称  
			out.write("loginName=admin&loginPassword=*****&validateCode=autoupdate"); // post的关键所在!  
			//remember to clean up  
			out.flush();  
			out.close();  
			
			//取得cookie,相当于记录了身份,供下次访问时使用  
			//HttpURLConnection.getHeaderFields()).get("Set-Cookie")用于迭代读取Cookie,为以后使用
			//HttpURLConnection.getHeaderField("Set-Cookie")也可用于读取Cookie,但不一定能读取完全
			String cookieVal = connection.getHeaderField("Set-Cookie");  //格式:JSESSIONID=541884418E77E7F07363CCEE91D4FF7E; Path=/
			connection.disconnect();
			
			//登陆成功后,即可访问其他URL了。
			String s = "http://192.168.5.40:8090/ylysystem/cms/systemsetting/u_cmsInput.sc?" +
					"buildType=date&maxResults=10&firstResult=0&buildContent=index" +
					"&beginDate=2013-03-13&endDate=2013-03-20";  
			//重新打开一个连接  
			url = new URL(s);  
			HttpURLConnection resumeConnection = (HttpURLConnection) url
			      .openConnection();  
			if (cookieVal != null) {  
			     //发送cookie信息上去,以表明自己的身份,否则会被认为没有权限  
			  resumeConnection.setRequestProperty("Cookie", cookieVal);//设置登陆配置	
			}
			resumeConnection.connect();  
			InputStream urlStream = resumeConnection.getInputStream();  
			BufferedReader bufferedReader = new BufferedReader(  
			      new InputStreamReader(urlStream));  
			String ss = null;  
			String total = "";  
			while ((ss = bufferedReader.readLine()) != null) {  
				System.err.println(ss);
				total += ss;  
			}  
			IOUtils.write(total, new FileOutputStream("d:/index.html"));  
			bufferedReader.close(); 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值