一个简单的验证码识别接口
1.识别验证码service
package com.fn.service;
/**
* @ClassName: IdentifyCode
* @Author: lxh
* @Description: 识别验证码service
* @Date: 2021/7/6 17:06
*/
public interface IdentifyCodeService {
/**
* 识别验证码接口
* @param imagePath
* @return java.lang.String
* @author lxh
*/
String identifyVerificationCode(String imagePath);
}
2.识别验证码impl,实现IdentifyCodeService接口
所有相关配置都在Nacos配置中心配置,通过@Value("${url.identifyUrl}") 去调用
url:
identifyUrl: http://101.201.223.138:9188/api/captcha/simple-captcha
headers:
appKey: 0c57a4fa-ada0-11eb-ad0f-7429af540200
appSecret: e962c9da567a8cebf39d24e8ca0f488d
package com.fn.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.fn.service.IdentifyCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @ClassName: IdentifyCodeServiceImpl
* @Author: lxh
* @Description: 识别验证码impl
* @Date: 2021/7/6 17:10
*/
@Service
public class IdentifyCodeServiceImpl implements IdentifyCodeService {
Logger logger = LoggerFactory.getLogger(IdentifyCodeServiceImpl.class);
@Value("${url.identifyUrl}")
private String identifyUrl;
@Value("${headers.appKey}")
private String appKey;
@Value("${headers.appSecret}")
private String appSecret;
/**
* 解析验证码实体
* @param imagePath
* @return java.lang.String(返回解析出来的验证码)
* @author lxh
* @date 2021/7/29 13:56
*/
@Override
public String identifyVerificationCode(String imagePath) {
//解析验证码
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("appKey", appKey);
headers.add("appSecret", appSecret);
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject body = new JSONObject();
body.put("urlimg", "data:image/png;base64," + convertFileToBase64(imagePath));
body.put("num", 4);
body.put("type", "603");
body.put("url", "http://xxxxx");
HttpEntity<String> formEntity = new HttpEntity<String>(body.toString(), headers);
ResponseEntity<JSONObject> responseEntity = template.exchange(identifyUrl, HttpMethod.POST, formEntity, JSONObject.class);
String code = responseEntity.getBody().getString("v_code");
logger.info("解析验证码:{}", code);
return code;
}
/**
* Base64编码
*/
public String convertFileToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组进行Base64编码,得到Base64编码的字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64Str = encoder.encode(data);
return base64Str;
}
}