java模拟登录内部系统抓取网页内容

@Component
public class Login  extends BaseJobs {
 
     SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" ); 
     /**
      * 获取当月第一天
     
      * @return
      */ 
     public String getFirstDayOfMonth() { 
         Calendar lastDate = Calendar.getInstance(); 
         lastDate.set(Calendar.DATE, 1 ); // 设为当前月的1号 
         return sdf.format(lastDate.getTime()); 
 
    
 
     /**
      * 计算当月最后一天
      * @return
      */ 
     public String getLastDayOfMonth() { 
 
         Calendar lastDate = Calendar.getInstance(); 
         lastDate.set(Calendar.DATE, 1 ); // 设为当前月的1号 
         lastDate.add(Calendar.MONTH, 1 ); // 加一个月,变为下月的1号 
         lastDate.add(Calendar.DATE, - 1 ); // 减去一天,变为当月最后一天 
         return sdf.format(lastDate.getTime()); 
 
    
 
     //测试
     public static void main(String args[]) throws Exception {
         Login l = new Login();
          l.login();
     }
 
 
     private static CookieStore cs = new BasicCookieStore();
 
     //利用spring定时器 每天早上10点一刻抓取并发邮件
     @Scheduled (cron = "0 15 10 ? * *" )
     public void login() throws Exception {
         DefaultHttpClient httpclient = new DefaultHttpClient();
 
         // 创建一个本地上下文信息
         HttpContext localContext = new BasicHttpContext();
         // 在本地上下问中绑定一个本地存储
         localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
         // 目标地址
         HttpPost httppost = new HttpPost(
                 "http://***/userLogin.do" );
         // 传参
         StringEntity reqEntity = new StringEntity(
                 "userName=jianancun&password=123456&randNum=565656" );
         // 设置类型
         reqEntity.setContentType( "application/x-www-form-urlencoded" );
         // 设置请求的数据
         httppost.setEntity(reqEntity);
         // 执行
         HttpResponse response = httpclient.execute(httppost);
         //取得所有头内容
         Header[] headers = response.getAllHeaders();
         for (Header h : headers) {
             String name = h.getName();
             String value = h.getValue();
             System.out.println( "header : " + h.getName() + ":" + h.getValue());
             if ( "Set-Cookie" .equalsIgnoreCase(name)) {
                 String[] strs = value.split( ";" );
                 for (String str : strs) {
                     String[] cookies = str.split( "=" );
                     //输出cookie名称及标题
                    // System.out.println("=============== : " + cookies[0] + ":" + cookies[1]);
                     cs.addCookie( new BasicClientCookie(cookies[ 0 ], cookies[ 1 ]));
                 }
                 cs.addCookie( new BasicClientCookie( "userId" , "8888" ));
                 cs.addCookie( new BasicClientCookie( "userName" , "jiannancun" ));
                 cs.addCookie( new BasicClientCookie( "state" , "0" ));
                 cs.addCookie( new BasicClientCookie( "iAdmin" , "0" ));
                 cs.addCookie( new BasicClientCookie( "depCode" , "0" ));
             }
         }
         HttpEntity entity = response.getEntity();
         // 显示结果
         BufferedReader reader = new BufferedReader( new InputStreamReader(
                 entity.getContent(), "UTF-8" ));
         String line = null ;
         //返回是否登录成功的内容 忽略
         while ((line = reader.readLine()) != null ) {
           //  System.out.println(line);
         }
 
 
 
        //可以添加多个用户
        String jlc[] ={URLEncoder.encode( "贱男春" ), "jiannancun@*.cn" , "888888" };
        List<String[]> list = new ArrayList<String[]>();
        list.add(jlc);
 
        for (String []u:list){
            //查询本月考勤内容
            String logPath = "http://**.cn/timeCard.jsp?nickName=" +u[ 0 ]+ "&eplTimeCard="
            +u[ 2 ]+ "&begDate=" +getFirstDayOfMonth()+ "&endDate=" +getLastDayOfMonth();
            String content= getContent(logPath);
             Document doc = Jsoup.parse(content);
             Elements tds = doc.select( "table td" );
             int i = 0 ;
             //返回的内容
             String html = "" ; ;
              for (Element td : tds) {
                 //取前25行内容   前25行内容显示的是昨天和今天的考勤记录
                  if (i< 25 ){
                   html+=td.text().replace(u[ 2 ],URLDecoder.decode(u[ 0 ]))+ "<br>" ;
                  } else break ;
 
                  i++;
              }
             Map<String,Object> map = new HashMap<String,Object>();
                 map.put( "mailTo" ,u[ 1 ]);
                 map.put( "mailTitle" , "考勤提醒" );
                 map.put( "messageBody" ,html);
                 //发送邮件
                 //sendMail(map);
        }
     }
     /**
      *  Function: 请求地址并返回页面内容
      @author JNC
      @param url
      @return
      @throws Exception
      */
     private String getContent(String url) throws Exception {
         DefaultHttpClient httpclient = new DefaultHttpClient();
         String cookieStr = "" ;
         List<Cookie> list = cs.getCookies();
         for (Cookie cookie : list) {
             cookieStr += cookie.getName() + "=" + cookie.getValue() + ";" ;
         }
         // 请求目标地址并带上cookie
         HttpGet httpget = new HttpGet(url);
         httpget.setHeader( "Cookie" , cookieStr);
         // 执行
         HttpResponse response = httpclient.execute(httpget);
         HttpEntity entity = response.getEntity();
         String resultStr = "" ;
         BufferedReader reader = new BufferedReader( new InputStreamReader(
                 entity.getContent(), "UTF-8" ));
         String line = null ;
         while ((line = reader.readLine()) != null ) {
             resultStr+=line;
         }
        return resultStr;
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java的Mock测试中,要获取无返回值方法内部定义的变量或对象,可以通过模拟方法的行为来实现。Mock测试通常使用Mock框架,如Mockito,来实现对方法的模拟。下面是一些可能有用的方法和技巧: 1. 使用Mockito的doAnswer方法:该方法可以模拟方法的行为,并使用Lambda表达式来获取方法内部定义的变量或对象。例如: ``` @Test public void testMethod() { MyClass myClass = mock(MyClass.class); doAnswer(invocation -> { Object[] args = invocation.getArguments(); // 在这里可以获取方法内部定义的变量或对象 return null; }).when(myClass).myVoidMethod(); myClass.myVoidMethod(); } ``` 2. 使用Mockito的ArgumentCaptor:该类可以用于捕获方法调用时的参数,并在测试中进行断言。例如: ``` @Test public void testMethod() { MyClass myClass = mock(MyClass.class); ArgumentCaptor<MyObject> captor = ArgumentCaptor.forClass(MyObject.class); doNothing().when(myClass).myVoidMethod(captor.capture()); MyObject obj = new MyObject(); myClass.myVoidMethod(obj); // 在这里可以获取方法内部定义的变量或对象 assertEquals(obj, captor.getValue()); } ``` 需要注意的是,在Mock测试中获取方法内部定义的变量或对象可能会破坏测试的封装性。如果变量或对象不是方法的输出,而只是中间过程的一部分,最好不要直接获取它们,而是通过Mock对象来模拟它们的行为。这样可以更好地保持测试的独立性和可重复性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值