2019/1/6 初探JAVA京东 httpclient 登陆(扫码登陆备用篇)

       上篇,我们讲到考虑京东随时得可变性,这里考虑长久,采用一个扫码登陆,登陆后,长期保持连接基本 一周登陆一次即可

直接上代码

public  static HttpClientUtil incodelogin(HttpClientUtil httpClient,UuserJDinfo uuserJDinfo) throws InterruptedException, IllegalStateException, IOException{
		boolean issmlogin =true;
		while (issmlogin) {//死循环登陆
		    Document doc = Jsoup.parse(httpClient.doGet("https://passport.jd.com/new/login.aspx"));
			Elements elements = doc.select("form[id=formlogin] input[type=hidden]");
                        //获得初始化参数
			Map map = new HashMap();
		       String k, v;
		        for (Element input : elements) {
		            k = input.attr("name");
		            v = input.attr("value");
		            if (StringUtils.isNotBlank(k)) {
		                map.put(k, v);
//		                System.out.println(input);
		            }
		        }

		        //得到二维码图片,PC登陆
		  HttpResponse response  =httpClient.getForResponse("https://qr.m.jd.com/show?appid=133&size=147&t=" + Math.random(),null);
		  InputStream inputStream = response.getEntity().getContent();
	      String name = "监控扫码登陆.png";
	      saveToImgByInputStream(inputStream,"D:\\",name);  //保存扫码图片到磁盘
	      String token="";
              //获得一个需要得参数 wlfstk_smdl 
	      List cookies = httpClient.getCookieStore().getCookies();    
	      if (!cookies.isEmpty()) {
	    	  for (int i = 0; i < cookies.size(); i++) {   
	    		  System.out.println(cookies.get(i).toString());
	    		  if(cookies.get(i).toString().indexOf("wlfstk_smdl")>-1){
	    			  String sss = cookies.get(i).toString().substring(cookies.get(i).toString().indexOf("value:")+7,cookies.get(i).toString().length());
	    			  token =sss.substring(0,sss.indexOf("]"));
	    			  System.out.println(token);
	    		  }
	    	  }
	      }
              //拿到参数后开始进行 心跳监听
	      Map head = new HashMap(); 
	      head.put("Referer", "https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F");
	      //开始监听 心跳监听
	      String ticket ="";
	      boolean isjt = true;
	      int isgq=0;
	      while (isjt) {
	    	String url ="https://qr.m.jd.com/check?callback=jQuery7661835&appid=133&token="+token+"&_="+new Date().getTime();
	    	String sss= httpClient.doGet(url,null,head);
	    	if(sss.indexOf("ticket") >-1){
	    		ticket=sss.substring(sss.indexOf("ticket\" : \"")+11,sss.length()-4);
	    		isjt =false;
	    	}else if(sss.indexOf("二维码过期") >-1){
	    		isgq=1;
	    	}	
	    	if(isgq==1){
	    		break;  
		    }
	    	Thread.sleep(2000);
	      }
                //登陆成功后获得所有 ck
	      String urlck ="https://passport.jd.com/uc/qrCodeTicketValidation?t="+ticket;
	      httpClient.doGet(urlck,null,head);
	      //判断是否登陆成功
	      if(islogin(httpClient)){
	    	  issmlogin =false;
	      }else{
	    	  issmlogin =true;
	      }
		}
		return httpClient;
	}
	

 

大神勿喷,代码比较匆忙 ! 

有技术交流可以加QQ:237240804 互相学习

你可能感兴趣的:(京东)