最近做问卷星的集成的时候碰到一个获取答卷的需求,但是问卷星的文档给的太粗糙了,例子是用的C#写的,我需要的是Java,因此我自己写了一个例子。
问卷星API—答卷提交后跳转并获取答卷数据(Java集成)
打开问卷星的API地址 问卷星API总览_旗舰版服务_API_创建调查问卷入门_使用流程_帮助中心_问卷星
找到我们需要的API
找到对应的配置端,这里需要有权限,如果没有,需要找负责人开通。
然后看到API中对答卷数据的处理,是加密过的,需要接收和解密。但是例子是用C#写的,和需求不一致,因此要根据API写出一个Java版本的。
注意看这里的解析:
下面是快速书写步骤:
- 配置问卷星地址,需要一个可以访问的地址,我用的是公网做测试,做了单点登录的是可以配置内网的,需要有权限。就是去配置一个问卷,然后点击问卷设置的时候有一个post答卷到该地址的选项,那个地址就填需要接收和解析答卷的地址。(由于保密问题,这里配置步骤不能截图)
- 得到问卷星的AESKEY,在配置问卷的地方有。
- 新建一个SpringBoot项目,导入一些基础的依赖就可以了,这里看个人需求,我测试是把原数据和解析后的数据都存起来,然后保存一下日志,所以用到了这几个依赖:
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
- 写一下保存数据到数据库信息的代码后,进行接收数据和解析,保存数据就不写了,直接看接收和解析。
@RestController @RequestMapping("/wjx") @Slf4j public class WjxContentController { @Resource private WjxContentService contentService; private String aesKey="xxxxxx";//这里是问卷配置的时候可以获取到的 @PostMapping(value = "/save",consumes = "application/x-www-form-urlencoded") public void save(@RequestParam String content) throws Exception { System.out.println(content); log.info("content:{}",content); //获取到被AES加密后的base64编码 byte[] base64Data = Base64.getDecoder().decode(content); // 取AES加解密密钥作为AES解密的KEY byte[] keyData = aesKey.getBytes(StandardCharsets.UTF_8); SecretKeySpec key = new SecretKeySpec(keyData, "AES"); // 取byte[] encryptedData的前16位做为IV byte[] iv = new byte[16]; System.arraycopy(base64Data, 0, iv, 0, 16); // 取第16位后的字节数组做为待解密内容 byte[] encryptedText = new byte[base64Data.length - 16]; System.arraycopy(base64Data, 16, encryptedText, 0, encryptedText.length); // 解密模式使用CBC,填充模式使用PKCS#7 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); // 使用配置好的实例化AES对象执行解密 byte[] decrypted = cipher.doFinal(encryptedText); // 使用UTF-8的方式读取二进制数组得到原始数据 String originalData = new String(decrypted, StandardCharsets.UTF_8); System.out.println("解析后的数据:" + originalData); WjxContent wjxContent = new WjxContent(); wjxContent.setContent(content); wjxContent.setCreateTime(new Date()); wjxContent.setResolveData(originalData); contentService.save(wjxContent); }