JAVA实现web登陆

  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();
  }
  结束语:
   上面的代码基本就可以实现网站的登陆、信息获取的功能。看到登陆奇兵等软件卖的那么火,我们也做一个去吧


  参考:
  1.A recipe for cookie management
http://www.javaworld.com/javaworld/jw-04-2002/jw-0426-cookie.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值