通过发送请求的形式执行某些相关操作,
这里用到了两种,包括Get和Post
下面进行说明
Get:
1 @Autowired//根据类型匹配需要配合Qualifier 2 //@Qualifier//名称 3 //@Resource//根据名称自动匹配,区别于@Autowired 4 public GetCaptcha Captcha; 5 6 @GetMapping("Captcha")//等同于下面 7 //@RequestMapping(value = "name",method = RequestMethod.GET) 8 public @ResponseBody String index(HttpServletRequest request){ //错误需要另外处理 9 10 //初始化11 HttpClient httpClient = Captcha.GetHttpClient();12 CaptchaData captchaData = new CaptchaData();13 captchaData.setHttpClient(httpClient);14 15 if(httpClient==null){16 return "创建对象错误,检查代理是否到期";17 }18 19 CaptchaData imgValue = Captcha.GetCaptcha(captchaData);20 21 request.getSession().setAttribute("captchaData",imgValue);22 23 String htmlText = imgValue.getImg()+"";28 return htmlText;//返回视图名称29 }
初始化HTTPClient信息,包括不限于:Proxy、SSL、访问头信息。。。。等
1 HttpClient httpClient = Captcha.GetHttpClient();
下面是我所用的设置信息
1 //初始化httpClient对象 2 public HttpClient GetHttpClient() { 3 //创建HTTPClient对象, 4 //初始化 5 SslContextFactory sslContextFactory = new SslContextFactory(); 6 sslContextFactory.setTrustAll(true); 7 HttpClient httpClient = new HttpClient(sslContextFactory); 8 httpClient.setConnectTimeout(10000); 9 httpClient.setFollowRedirects(true);10 httpClient.setUserAgentField(new HttpField("User-Agent", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));11 12 ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();13 HttpProxy proxy = new HttpProxy("xx.xx.xx.xx", xxx);14 proxyConfig.getProxies().add(proxy);15 try {16 httpClient.start();17 return httpClient;18 } catch (Exception e) {19 return null;20 }21 22 }
因要写成Server服务的形式,存在多名用户相互访问的情况,需要将某些信息保存在Session种加以区分。
又因需要传递多个参数,且参数类型不一致,故才采用对象的形式传递,设置CaptchaData进行存储和传递参数
获取的验证码以Baes64存储和展示。
Get请求实现
1 CaptchaData imgValue = Captcha.GetCaptcha(captchaData);
获取信息后返回给请求主体。
Post:
Post与Get的区别在于可以获取数据信息。
1 @PostMapping("json") 2 public @ResponseBody String resp(Userdb user,HttpServletRequest request){ 3 4 CaptchaData captchaData = (CaptchaData) request.getSession().getAttribute("captchaData"); 5 HttpClient httpClient = captchaData.getHttpClient(); 6 7 String returnValue = ""; 8 try { 9 returnValue = Captcha.PostData(user,captchaData);10 }catch (Exception e){11 returnValue = "数据传输出现错误,请检查数据信息";12 }finally {13 try{14 httpClient.stop();15 }16 catch (Exception e){17 returnValue += " \n HttpClient关闭异常";18 }19 }20 return returnValue;21 }
以表单形式传递参数可以在读取时设定相对应的名称来获取,可以对数值进行限定(不为空,在某个值范围之内)
最后贴出自己的pom.xml配置信息
1 23 7 8org.springframework.boot 4spring-boot-starter-parent 51.5.9.RELEASE 69 10 11 21 22org.springframework.boot 12spring-boot-starter-web 13 1415 2016 19org.springframework.boot 17spring-boot-starter-tomcat 1823 26org.springframework.boot 24spring-boot-starter-jetty 2527 31 32 33org.springframework.boot 28spring-boot-starter-test 29test 3034 38 39org.jsoup 35jsoup 361.10.3 37
这里必须移除默认的Tomcat容器,否则会产生异常错误
。
END