parent
0318f7181b
commit
f3a746481c
15 changed files with 968 additions and 5 deletions
@ -0,0 +1,40 @@ |
||||
package com.huoran.users.config; |
||||
|
||||
import org.apache.commons.codec.binary.Base64; |
||||
import org.springframework.web.multipart.MultipartFile; |
||||
|
||||
import java.io.IOException; |
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
|
||||
public class AliRealNameAuthenticationConfig { |
||||
public static final String ALI_API_HOST = "https://cardnumber.market.alicloudapi.com"; |
||||
|
||||
|
||||
public static final String ALI_API_PATH = "/rest/160601/ocr/ocr_idcard.json"; |
||||
public static final String ALI_API_APPCODE = "4c22c2b34b2d4b5aaa57186a49aa3a4c"; |
||||
|
||||
public static final String ALI_IDCHECK_HOST = "https://sxidcheck.market.alicloudapi.com"; |
||||
public static final String ALI_IDCHECK_PATH = "/idcard/check"; |
||||
|
||||
public static final String GET_APP_CODE_LINK = "https://idenauthen.market.alicloudapi.com/idenAuthentication"; |
||||
|
||||
public static Map<String, String> buildHeaders() { |
||||
Map<String, String> headers = new HashMap<>(); |
||||
headers.put("Authorization", "APPCODE " + ALI_API_APPCODE); |
||||
headers.put("Content-Type", "application/json; charset=UTF-8"); |
||||
return headers; |
||||
} |
||||
|
||||
public static String imgBase64(MultipartFile file) { |
||||
String imgBase64 = ""; |
||||
try { |
||||
byte[] content = file.getBytes(); |
||||
imgBase64 = new String(Base64.encodeBase64(content)); |
||||
} catch (IOException e) { |
||||
e.printStackTrace(); |
||||
} |
||||
return imgBase64; |
||||
} |
||||
} |
@ -0,0 +1,111 @@ |
||||
package com.huoran.users.controller; |
||||
|
||||
import com.google.gson.Gson; |
||||
import com.huoran.common.response.R; |
||||
import com.huoran.common.utils.TokenUtils; |
||||
import com.huoran.users.config.AliRealNameAuthenticationConfig; |
||||
import com.huoran.users.entity.UserAuthenticationInformation; |
||||
import com.huoran.users.entity.req.IdCardOCRReq; |
||||
import com.huoran.users.entity.res.IdCardOCRResp; |
||||
import com.huoran.users.entity.res.RealNameAuthenticationResp; |
||||
import com.huoran.users.service.UserAuthenticationInformationService; |
||||
import com.huoran.users.utils.ali.FaceRecognitionAidUtil; |
||||
import io.swagger.annotations.Api; |
||||
import io.swagger.annotations.ApiOperation; |
||||
import io.swagger.annotations.ApiParam; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.util.ObjectUtils; |
||||
import org.springframework.web.bind.annotation.*; |
||||
|
||||
import javax.servlet.http.HttpServletRequest; |
||||
import java.io.IOException; |
||||
import java.util.Optional; |
||||
|
||||
@Api(value = "小程序-实名认证", tags = "小程序-实名认证") |
||||
@RestController |
||||
@RequestMapping("/users/autonym") |
||||
public class AliRealNameAuthenticationController { |
||||
|
||||
//实名认证实现类
|
||||
@Autowired |
||||
public UserAuthenticationInformationService service; |
||||
|
||||
@ApiOperation(value = "身份证图片验证(对象)") |
||||
@PostMapping("/faceAuthenticationByObject") |
||||
public R faceAuthenticationByObject(HttpServletRequest request, @RequestBody IdCardOCRReq req) throws IOException { |
||||
//正面身份证信息返回
|
||||
String positiveIDReturnsInformation = FaceRecognitionAidUtil.IdCardOCRRecognition(req.getTheFrontOfIDCard(),"face"); |
||||
|
||||
//反面身份证信息返回
|
||||
String reverseIDInformationReturned = FaceRecognitionAidUtil.IdCardOCRRecognition(req.getReverseOfIDCard(),"back"); |
||||
|
||||
/*if (ObjectUtils.isEmpty(positiveIDReturnsInformation)&&ObjectUtils.isEmpty(reverseIDInformationReturned)){ |
||||
throw new RuntimeException("身份证图片验证失败,请重新再试!"); |
||||
}*/ |
||||
Optional.ofNullable(positiveIDReturnsInformation) |
||||
.orElseThrow(() -> new RuntimeException("身份证图片验证失败,请重新再试!")); |
||||
Optional.ofNullable(reverseIDInformationReturned) |
||||
.orElseThrow(() -> new RuntimeException("身份证图片验证失败,请重新再试!")); |
||||
|
||||
IdCardOCRResp front = new Gson().fromJson(positiveIDReturnsInformation, IdCardOCRResp.class); |
||||
|
||||
IdCardOCRResp reverseSide = new Gson().fromJson(reverseIDInformationReturned, IdCardOCRResp.class); |
||||
|
||||
return R.ok().put("front", front).put("reverseSide", reverseSide); |
||||
} |
||||
|
||||
@ApiOperation(value = "身份证图片验证") |
||||
@PostMapping("/faceAuthentication") |
||||
public R faceAuthentication(@RequestParam(name = "imgFile", required = true) @ApiParam(value = "图片url") String imgFile , |
||||
@RequestParam(name = "side", required = true) @ApiParam(value = "身份证正反面类型:face/back") String side)throws IOException { |
||||
//身份证信息返回
|
||||
String idCardInformationReturn = FaceRecognitionAidUtil.IdCardOCRRecognition(imgFile,side); |
||||
if (ObjectUtils.isEmpty(idCardInformationReturn)){ |
||||
throw new RuntimeException("身份证图片验证失败,请重新再试!"); |
||||
} |
||||
IdCardOCRResp resp = new Gson().fromJson(idCardInformationReturn, IdCardOCRResp.class); |
||||
if (resp.getSuccess()){ |
||||
return R.ok().put("data", resp); |
||||
}else { |
||||
throw new RuntimeException("身份证图片验证失败,请重新再试!"); |
||||
} |
||||
|
||||
} |
||||
|
||||
|
||||
@PostMapping("/realNameAuthentication") |
||||
@ApiOperation(value = "输入身份证号码、姓名进行实名认证且添加认证信息", response = UserAuthenticationInformation.class) |
||||
public R realNameAuthentication(@RequestBody @ApiParam(name = "用户实名认证信息记录对象", value = "传入json格式", required = true) UserAuthenticationInformation userAuthenticationInformation, HttpServletRequest request) throws IOException { |
||||
String accountId = TokenUtils.getIdByJwtToken(request); |
||||
userAuthenticationInformation.setAccountId(Integer.valueOf(accountId)); |
||||
|
||||
String json = FaceRecognitionAidUtil.postData(AliRealNameAuthenticationConfig.ALI_API_APPCODE, |
||||
AliRealNameAuthenticationConfig.GET_APP_CODE_LINK, userAuthenticationInformation.getRealName(), userAuthenticationInformation.getIdCardNo()); |
||||
RealNameAuthenticationResp info = new Gson().fromJson(json, RealNameAuthenticationResp.class); |
||||
|
||||
if (!info.getRespCode().equals("0000")) { |
||||
throw new RuntimeException(info.getRespMessage()); |
||||
} |
||||
|
||||
|
||||
boolean addState = service.save(userAuthenticationInformation); |
||||
return addState ? R.ok() : R.error("认证失败"); |
||||
} |
||||
|
||||
|
||||
/*@ApiOperation(value = "输入身份证号码、姓名进行实名认证") |
||||
@PostMapping("/realNameAuthentication") |
||||
public R realNameAuthentication(@RequestParam(name = "idCardNo", required = true) @ApiParam(value = "身份证号码") String idCardNo, @RequestParam(name = "userName", required = true) @ApiParam(value = "用户姓名") String userName, HttpServletRequest request) throws IOException { |
||||
String accountId = TokenUtils.getIdByJwtToken(request); |
||||
String json = FaceRecognitionAidUtil.postData(AliRealNameAuthenticationConfig.ALI_API_APPCODE, AliRealNameAuthenticationConfig.GET_APP_CODE_LINK, userName, idCardNo); |
||||
RealNameAuthenticationResp info = new Gson().fromJson(json, RealNameAuthenticationResp.class); |
||||
|
||||
if (!info.getRespCode().equals("0000")) { |
||||
throw new RuntimeException(info.getRespMessage()); |
||||
} |
||||
return R.ok().put("data", info); |
||||
|
||||
}*/ |
||||
|
||||
|
||||
} |
@ -0,0 +1,63 @@ |
||||
package com.huoran.users.controller; |
||||
|
||||
import com.huoran.api.UserClient; |
||||
import com.huoran.common.response.R; |
||||
import com.huoran.common.utils.TokenUtils; |
||||
import com.huoran.users.entity.UserAuthenticationInformation; |
||||
import com.huoran.users.service.UserAuthenticationInformationService; |
||||
import io.swagger.annotations.Api; |
||||
import io.swagger.annotations.ApiOperation; |
||||
import io.swagger.annotations.ApiParam; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.web.bind.annotation.*; |
||||
|
||||
import javax.servlet.http.HttpServletRequest; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @描述:用户实名认证信息记录控制类 |
||||
* @作者: Rong |
||||
* @日期: 2023-12-14 |
||||
*/ |
||||
@RestController |
||||
@RequestMapping("/userAuthenticationInformation") |
||||
@Api(value = "用户实名认证信息记录:UserAuthenticationInformationController", tags = "用户实名认证信息记录") |
||||
public class UserAuthenticationInformationController { |
||||
|
||||
@Autowired |
||||
public UserAuthenticationInformationService service; |
||||
|
||||
@Autowired |
||||
private UserClient userClient; |
||||
|
||||
|
||||
@PostMapping("/findById") |
||||
@ApiOperation(value = "查询详情", response = UserAuthenticationInformation.class) |
||||
public R findById(@ApiParam(name = "id", value = "主键", required = true) @RequestParam Integer id) { |
||||
UserAuthenticationInformation userAuthenticationInformation = service.getById(id); |
||||
return R.ok().put("data", userAuthenticationInformation); |
||||
} |
||||
|
||||
|
||||
@PostMapping("/save") |
||||
@ApiOperation(value = "新增", response = UserAuthenticationInformation.class) |
||||
public R save(@RequestBody @ApiParam(name = "用户实名认证信息记录对象", value = "传入json格式", required = true) UserAuthenticationInformation userAuthenticationInformation, HttpServletRequest request) { |
||||
String accountId = TokenUtils.getIdByJwtToken(request); |
||||
Integer schoolId = userClient.getSchoolIdByAccountId(accountId); |
||||
userAuthenticationInformation.setAccountId(Integer.valueOf(accountId)); |
||||
boolean addState = service.save(userAuthenticationInformation); |
||||
return addState ? R.ok() : R.error("新增失败"); |
||||
} |
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@PostMapping("/batchDeletion") |
||||
@ApiOperation(value = "批量删除", response = UserAuthenticationInformation.class) |
||||
public R batchDeletion(@ApiParam(name = "ids", value = "主键", required = true) @RequestBody List<Integer> ids) { |
||||
boolean delState = service.removeByIds(ids); |
||||
return delState ? R.ok() : R.error("删除失败"); |
||||
} |
||||
} |
||||
|
@ -0,0 +1,87 @@ |
||||
package com.huoran.users.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
import com.baomidou.mybatisplus.annotation.IdType; |
||||
import java.util.Date; |
||||
import com.baomidou.mybatisplus.annotation.TableId; |
||||
import java.io.Serializable; |
||||
import io.swagger.annotations.ApiModel; |
||||
import io.swagger.annotations.ApiModelProperty; |
||||
import lombok.Data; |
||||
import lombok.EqualsAndHashCode; |
||||
import lombok.experimental.Accessors; |
||||
|
||||
/** |
||||
* <p> |
||||
* 用户实名认证信息记录 |
||||
* </p> |
||||
* |
||||
* @author chen |
||||
* @since 2023-12-14 |
||||
*/ |
||||
@Data |
||||
@EqualsAndHashCode(callSuper = false) |
||||
@Accessors(chain = true) |
||||
@TableName("hr_user_authentication_information") |
||||
@ApiModel(value="UserAuthenticationInformation对象", description="用户实名认证信息记录") |
||||
public class UserAuthenticationInformation implements Serializable { |
||||
|
||||
private static final long serialVersionUID = 1L; |
||||
|
||||
@ApiModelProperty(value = "主键") |
||||
@TableId(value = "id", type = IdType.AUTO) |
||||
private Integer id; |
||||
|
||||
@ApiModelProperty(value = "账号id") |
||||
private Integer accountId; |
||||
|
||||
@ApiModelProperty(value = "姓名") |
||||
private String realName; |
||||
|
||||
@ApiModelProperty(value = "身份证号码") |
||||
private String idCardNo; |
||||
|
||||
@ApiModelProperty(value = "生日") |
||||
private Date birthday; |
||||
|
||||
@ApiModelProperty(value = "年龄") |
||||
private Integer age; |
||||
|
||||
@ApiModelProperty(value = "性别") |
||||
private String sex; |
||||
|
||||
@ApiModelProperty(value = "省") |
||||
private String province; |
||||
|
||||
@ApiModelProperty(value = "市") |
||||
private String city; |
||||
|
||||
@ApiModelProperty(value = "县") |
||||
private String county; |
||||
|
||||
@ApiModelProperty(value = "地址信息") |
||||
private String address; |
||||
|
||||
@ApiModelProperty(value = "民族") |
||||
private String nationality; |
||||
|
||||
@ApiModelProperty(value = "有效期起始时间") |
||||
private Date startDate; |
||||
|
||||
@ApiModelProperty(value = "有效期结束时间") |
||||
private Date endDate; |
||||
|
||||
@ApiModelProperty(value = "签发机关") |
||||
private String issue; |
||||
|
||||
@ApiModelProperty(value = "身份证正面图片地址") |
||||
private String frontOfIdCard; |
||||
|
||||
@ApiModelProperty(value = "身份证反面图片地址") |
||||
private String reverseOfIdCard; |
||||
|
||||
@ApiModelProperty(value = "实名认证的时间") |
||||
private Date realNameAuthenticationTime; |
||||
|
||||
|
||||
} |
@ -0,0 +1,17 @@ |
||||
package com.huoran.users.entity.req; |
||||
|
||||
import io.swagger.annotations.ApiModel; |
||||
import io.swagger.annotations.ApiModelProperty; |
||||
import lombok.Data; |
||||
|
||||
@Data |
||||
@ApiModel(value = "身份证上传请求参数") |
||||
public class IdCardOCRReq { |
||||
@ApiModelProperty(value = "身份证正面") |
||||
private String theFrontOfIDCard; |
||||
|
||||
@ApiModelProperty(value = "身份证反面") |
||||
private String reverseOfIDCard; |
||||
|
||||
|
||||
} |
@ -0,0 +1,70 @@ |
||||
package com.huoran.users.entity.res; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore; |
||||
import io.swagger.annotations.ApiModel; |
||||
import io.swagger.annotations.ApiModelProperty; |
||||
import lombok.Data; |
||||
|
||||
@Data |
||||
@ApiModel(value = "身份证OCR文件识别") |
||||
public class IdCardOCRResp { |
||||
@ApiModelProperty(value = "地址信息") |
||||
private String address; |
||||
|
||||
@ApiModelProperty(value = "用户姓名") |
||||
private String name; |
||||
|
||||
@ApiModelProperty(value = "身份证号码") |
||||
private String num; |
||||
|
||||
@ApiModelProperty(value = "民族") |
||||
private String nationality; |
||||
|
||||
@ApiModelProperty(value = "配置信息,同输入configure") |
||||
private String config_str; |
||||
|
||||
@ApiModelProperty(value = "返回信息") |
||||
private String respMessage; |
||||
|
||||
@ApiModelProperty(value = "返回错误码") |
||||
private String respCode; |
||||
|
||||
@ApiModelProperty(value = "省") |
||||
private String province; |
||||
|
||||
@ApiModelProperty(value = "市") |
||||
private String city; |
||||
|
||||
@ApiModelProperty(value = "县/区") |
||||
private String county; |
||||
|
||||
@ApiModelProperty(value = "生日") |
||||
private String birth; |
||||
|
||||
@ApiModelProperty(value = "性别") |
||||
private String sex; |
||||
|
||||
@ApiModelProperty(value = "年龄") |
||||
private String age; |
||||
|
||||
@ApiModelProperty(value = "是否是复印件") |
||||
private String is_fake; |
||||
|
||||
@ApiModelProperty(value = "有效期起始时间") |
||||
private String start_date; |
||||
|
||||
@ApiModelProperty(value = "有效期结束时间") |
||||
private String end_date; |
||||
|
||||
@ApiModelProperty(value = "签发机关") |
||||
private String issue; |
||||
|
||||
|
||||
//使用@JsonIgnore注解,忽略此属性,前端不会拿到该属性
|
||||
@JsonIgnore |
||||
@ApiModelProperty(value = "识别结果,true表示成功,false表示失败") |
||||
private Boolean success; |
||||
|
||||
|
||||
|
||||
} |
@ -0,0 +1,42 @@ |
||||
package com.huoran.users.entity.res; |
||||
|
||||
import io.swagger.annotations.ApiModel; |
||||
import io.swagger.annotations.ApiModelProperty; |
||||
import lombok.Data; |
||||
|
||||
@Data |
||||
@ApiModel(value = "实名认证返回的信息") |
||||
public class RealNameAuthenticationResp { |
||||
@ApiModelProperty(value = "用户姓名") |
||||
private String name; |
||||
|
||||
@ApiModelProperty(value = "身份证号码") |
||||
private String idNo; |
||||
|
||||
|
||||
|
||||
@ApiModelProperty(value = "返回信息") |
||||
private String respMessage; |
||||
|
||||
@ApiModelProperty(value = "返回错误码") |
||||
private String respCode; |
||||
|
||||
@ApiModelProperty(value = "省") |
||||
private String province; |
||||
|
||||
@ApiModelProperty(value = "市") |
||||
private String city; |
||||
|
||||
@ApiModelProperty(value = "县/区") |
||||
private String county; |
||||
|
||||
@ApiModelProperty(value = "生日") |
||||
private String birthday; |
||||
|
||||
@ApiModelProperty(value = "性别") |
||||
private String sex; |
||||
|
||||
@ApiModelProperty(value = "年龄") |
||||
private String age; |
||||
|
||||
} |
@ -0,0 +1,16 @@ |
||||
package com.huoran.users.mapper; |
||||
|
||||
import com.huoran.users.entity.UserAuthenticationInformation; |
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
|
||||
/** |
||||
* <p> |
||||
* 用户实名认证信息记录 Mapper 接口 |
||||
* </p> |
||||
* |
||||
* @author chen |
||||
* @since 2023-12-14 |
||||
*/ |
||||
public interface UserAuthenticationInformationMapper extends BaseMapper<UserAuthenticationInformation> { |
||||
|
||||
} |
@ -0,0 +1,5 @@ |
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
||||
<mapper namespace="com.huoran.users.mapper.UserAuthenticationInformationMapper"> |
||||
|
||||
</mapper> |
@ -0,0 +1,16 @@ |
||||
package com.huoran.users.service; |
||||
|
||||
import com.huoran.users.entity.UserAuthenticationInformation; |
||||
import com.baomidou.mybatisplus.extension.service.IService; |
||||
|
||||
/** |
||||
* <p> |
||||
* 用户实名认证信息记录 服务类 |
||||
* </p> |
||||
* |
||||
* @author chen |
||||
* @since 2023-12-14 |
||||
*/ |
||||
public interface UserAuthenticationInformationService extends IService<UserAuthenticationInformation> { |
||||
|
||||
} |
@ -0,0 +1,20 @@ |
||||
package com.huoran.users.service.impl; |
||||
|
||||
import com.huoran.users.entity.UserAuthenticationInformation; |
||||
import com.huoran.users.mapper.UserAuthenticationInformationMapper; |
||||
import com.huoran.users.service.UserAuthenticationInformationService; |
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; |
||||
import org.springframework.stereotype.Service; |
||||
|
||||
/** |
||||
* <p> |
||||
* 用户实名认证信息记录 服务实现类 |
||||
* </p> |
||||
* |
||||
* @author chen |
||||
* @since 2023-12-14 |
||||
*/ |
||||
@Service |
||||
public class UserAuthenticationInformationServiceImpl extends ServiceImpl<UserAuthenticationInformationMapper, UserAuthenticationInformation> implements UserAuthenticationInformationService { |
||||
|
||||
} |
@ -0,0 +1,148 @@ |
||||
package com.huoran.users.utils.ali; |
||||
|
||||
import com.alibaba.fastjson.JSON; |
||||
import com.alibaba.fastjson.JSONObject; |
||||
import com.alibaba.nacos.client.identify.Base64; |
||||
import com.huoran.users.config.AliRealNameAuthenticationConfig; |
||||
import okhttp3.*; |
||||
import org.apache.http.HttpResponse; |
||||
import org.apache.http.util.EntityUtils; |
||||
|
||||
import java.io.File; |
||||
import java.io.FileInputStream; |
||||
import java.io.IOException; |
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
public class FaceRecognitionAidUtil { |
||||
public static String postData(String appCode, String url, String name, String idNo) throws IOException { |
||||
String result = ""; |
||||
RequestBody formBody = new FormBody.Builder().add("name", name).add("idNo", idNo).build(); |
||||
Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(formBody).build(); |
||||
|
||||
Call call = new OkHttpClient().newCall(request); |
||||
Response response = null; |
||||
try { |
||||
response = call.execute(); |
||||
} catch (IOException e) { |
||||
System.out.println("execute failed, message:" + e.getMessage()); |
||||
} |
||||
|
||||
assert response != null; |
||||
if (!response.isSuccessful()) { |
||||
// 状态码为403时一般是套餐包用尽,需续购;注意:续购不会改变秘钥(appCode),仅增加次数
|
||||
// 续购链接:https://market.aliyun.com/products/57000002/cmapi025518.html
|
||||
System.out.println("request failed----" + "返回状态码" + response.code() + ",message:" + response.message()); |
||||
} |
||||
result = response.body().string(); //此处不可以使用toString()方法,该方法已过期
|
||||
|
||||
return result; |
||||
} |
||||
|
||||
public static JSONObject checkIdcard(Object idcard, Object name) { |
||||
JSONObject result = new JSONObject(); |
||||
|
||||
Map<String, String> querys = new HashMap<>(); |
||||
querys.put("idCard", idcard.toString()); |
||||
querys.put("name", name.toString()); |
||||
|
||||
try { |
||||
HttpResponse response = HttpUtils.doPost(AliRealNameAuthenticationConfig.ALI_IDCHECK_HOST, AliRealNameAuthenticationConfig.ALI_IDCHECK_PATH, "POST", AliRealNameAuthenticationConfig.buildHeaders(), querys, new HashMap<>() // No need to pass an empty map for bodys
|
||||
); |
||||
|
||||
int stat = response.getStatusLine().getStatusCode(); |
||||
if (stat == 200) { |
||||
String res = EntityUtils.toString(response.getEntity()); |
||||
result = JSON.parseObject(res); |
||||
} else { |
||||
result.put("error", "Http code: " + stat); |
||||
result.put("message", EntityUtils.toString(response.getEntity())); |
||||
} |
||||
} catch (Exception e) { |
||||
result.put("error", "实名认证检测失败"); |
||||
result.put("message", e.getMessage()); |
||||
// 记录错误而不仅仅打印堆栈跟踪
|
||||
e.printStackTrace(); |
||||
} |
||||
|
||||
System.out.println(result); |
||||
return result; |
||||
} |
||||
|
||||
|
||||
|
||||
public static String img_base64(String path) { |
||||
/** |
||||
* 对path进行判断,如果是本地文件就二进制读取并base64编码,如果是url,则返回 |
||||
*/ |
||||
String imgBase64=""; |
||||
if (path.startsWith("http")){ |
||||
imgBase64 = path; |
||||
}else { |
||||
try { |
||||
File file = new File(path); |
||||
byte[] content = new byte[(int) file.length()]; |
||||
FileInputStream finputstream = new FileInputStream(file); |
||||
finputstream.read(content); |
||||
finputstream.close(); |
||||
imgBase64 = new String(Base64.encodeBase64(content)); |
||||
} catch (IOException e) { |
||||
e.printStackTrace(); |
||||
return imgBase64; |
||||
} |
||||
} |
||||
|
||||
return imgBase64; |
||||
} |
||||
|
||||
|
||||
|
||||
|
||||
public static String IdCardOCRRecognition(String imgFile,String side){ |
||||
String method = "POST"; |
||||
Map<String, String> headers = new HashMap<String, String>(); |
||||
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
|
||||
headers.put("Authorization", "APPCODE " + AliRealNameAuthenticationConfig.ALI_API_APPCODE); |
||||
//根据API的要求,定义相对应的Content-Type
|
||||
headers.put("Content-Type", "application/json; charset=UTF-8"); |
||||
|
||||
Map<String, String> querys = new HashMap<String, String>(); |
||||
// 对图像进行base64编码
|
||||
String imgBase64 = FaceRecognitionAidUtil.img_base64(imgFile); |
||||
|
||||
//configure配置
|
||||
JSONObject configObj = new JSONObject(); |
||||
// configObj.put("side", "face");
|
||||
configObj.put("side", side); |
||||
|
||||
String config_str = configObj.toString(); |
||||
|
||||
// 拼装请求body的json字符串
|
||||
JSONObject requestObj = new JSONObject(); |
||||
requestObj.put("image", imgBase64); |
||||
if (configObj.size() > 0) { |
||||
requestObj.put("configure", config_str); |
||||
} |
||||
String bodys = requestObj.toString(); |
||||
|
||||
try { |
||||
HttpResponse response = HttpUtils.doPost(AliRealNameAuthenticationConfig.ALI_API_HOST, AliRealNameAuthenticationConfig.ALI_API_PATH, method, headers, querys, bodys); |
||||
int stat = response.getStatusLine().getStatusCode(); |
||||
if (stat != 200) { |
||||
System.out.println("Http code: " + stat); |
||||
System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message")); |
||||
System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity())); |
||||
} |
||||
|
||||
String res = EntityUtils.toString(response.getEntity()); |
||||
/* JSONObject res_obj = JSON.parseObject(res); |
||||
|
||||
System.out.println(res_obj.toJSONString());*/ |
||||
return res; |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
} |
||||
|
||||
return null; |
||||
} |
||||
} |
@ -0,0 +1,313 @@ |
||||
package com.huoran.users.utils.ali; |
||||
|
||||
import java.io.UnsupportedEncodingException; |
||||
import java.net.URLEncoder; |
||||
import java.security.KeyManagementException; |
||||
import java.security.NoSuchAlgorithmException; |
||||
import java.security.cert.X509Certificate; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
import javax.net.ssl.SSLContext; |
||||
import javax.net.ssl.TrustManager; |
||||
import javax.net.ssl.X509TrustManager; |
||||
|
||||
import org.apache.commons.lang.StringUtils; |
||||
import org.apache.http.HttpResponse; |
||||
import org.apache.http.NameValuePair; |
||||
import org.apache.http.client.HttpClient; |
||||
import org.apache.http.client.entity.UrlEncodedFormEntity; |
||||
import org.apache.http.client.methods.HttpDelete; |
||||
import org.apache.http.client.methods.HttpGet; |
||||
import org.apache.http.client.methods.HttpPost; |
||||
import org.apache.http.client.methods.HttpPut; |
||||
import org.apache.http.conn.ClientConnectionManager; |
||||
import org.apache.http.conn.scheme.Scheme; |
||||
import org.apache.http.conn.scheme.SchemeRegistry; |
||||
import org.apache.http.conn.ssl.SSLSocketFactory; |
||||
import org.apache.http.entity.ByteArrayEntity; |
||||
import org.apache.http.entity.StringEntity; |
||||
import org.apache.http.impl.client.DefaultHttpClient; |
||||
import org.apache.http.message.BasicNameValuePair; |
||||
|
||||
@SuppressWarnings("deprecation") |
||||
public class HttpUtils { |
||||
|
||||
/** |
||||
* get |
||||
* |
||||
* @param host |
||||
* @param path |
||||
* @param method |
||||
* @param headers |
||||
* @param querys |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static HttpResponse doGet(String host, String path, String method, |
||||
Map<String, String> headers, |
||||
Map<String, String> querys) |
||||
throws Exception { |
||||
HttpClient httpClient = wrapClient(host); |
||||
|
||||
HttpGet request = new HttpGet(buildUrl(host, path, querys)); |
||||
for (Map.Entry<String, String> e : headers.entrySet()) { |
||||
request.addHeader(e.getKey(), e.getValue()); |
||||
} |
||||
|
||||
return httpClient.execute(request); |
||||
} |
||||
|
||||
/** |
||||
* post form |
||||
* |
||||
* @param host |
||||
* @param path |
||||
* @param method |
||||
* @param headers |
||||
* @param querys |
||||
* @param bodys |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static HttpResponse doPost(String host, String path, String method, |
||||
Map<String, String> headers, |
||||
Map<String, String> querys, |
||||
Map<String, String> bodys) |
||||
throws Exception { |
||||
HttpClient httpClient = wrapClient(host); |
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys)); |
||||
for (Map.Entry<String, String> e : headers.entrySet()) { |
||||
request.addHeader(e.getKey(), e.getValue()); |
||||
} |
||||
|
||||
if (bodys != null) { |
||||
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); |
||||
|
||||
for (String key : bodys.keySet()) { |
||||
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); |
||||
} |
||||
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); |
||||
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); |
||||
request.setEntity(formEntity); |
||||
} |
||||
|
||||
return httpClient.execute(request); |
||||
} |
||||
|
||||
/** |
||||
* Post String |
||||
* |
||||
* @param host |
||||
* @param path |
||||
* @param method |
||||
* @param headers |
||||
* @param querys |
||||
* @param body |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static HttpResponse doPost(String host, String path, String method, |
||||
Map<String, String> headers, |
||||
Map<String, String> querys, |
||||
String body) |
||||
throws Exception { |
||||
HttpClient httpClient = wrapClient(host); |
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys)); |
||||
for (Map.Entry<String, String> e : headers.entrySet()) { |
||||
request.addHeader(e.getKey(), e.getValue()); |
||||
} |
||||
|
||||
if (StringUtils.isNotBlank(body)) { |
||||
request.setEntity(new StringEntity(body, "utf-8")); |
||||
} |
||||
|
||||
return httpClient.execute(request); |
||||
} |
||||
|
||||
/** |
||||
* Post stream |
||||
* |
||||
* @param host |
||||
* @param path |
||||
* @param method |
||||
* @param headers |
||||
* @param querys |
||||
* @param body |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static HttpResponse doPost(String host, String path, String method, |
||||
Map<String, String> headers, |
||||
Map<String, String> querys, |
||||
byte[] body) |
||||
throws Exception { |
||||
HttpClient httpClient = wrapClient(host); |
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys)); |
||||
for (Map.Entry<String, String> e : headers.entrySet()) { |
||||
request.addHeader(e.getKey(), e.getValue()); |
||||
} |
||||
|
||||
if (body != null) { |
||||
request.setEntity(new ByteArrayEntity(body)); |
||||
} |
||||
|
||||
return httpClient.execute(request); |
||||
} |
||||
|
||||
/** |
||||
* Put String |
||||
* @param host |
||||
* @param path |
||||
* @param method |
||||
* @param headers |
||||
* @param querys |
||||
* @param body |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static HttpResponse doPut(String host, String path, String method, |
||||
Map<String, String> headers, |
||||
Map<String, String> querys, |
||||
String body) |
||||
throws Exception { |
||||
HttpClient httpClient = wrapClient(host); |
||||
|
||||
HttpPut request = new HttpPut(buildUrl(host, path, querys)); |
||||
for (Map.Entry<String, String> e : headers.entrySet()) { |
||||
request.addHeader(e.getKey(), e.getValue()); |
||||
} |
||||
|
||||
if (StringUtils.isNotBlank(body)) { |
||||
request.setEntity(new StringEntity(body, "utf-8")); |
||||
} |
||||
|
||||
return httpClient.execute(request); |
||||
} |
||||
|
||||
/** |
||||
* Put stream |
||||
* @param host |
||||
* @param path |
||||
* @param method |
||||
* @param headers |
||||
* @param querys |
||||
* @param body |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static HttpResponse doPut(String host, String path, String method, |
||||
Map<String, String> headers, |
||||
Map<String, String> querys, |
||||
byte[] body) |
||||
throws Exception { |
||||
HttpClient httpClient = wrapClient(host); |
||||
|
||||
HttpPut request = new HttpPut(buildUrl(host, path, querys)); |
||||
for (Map.Entry<String, String> e : headers.entrySet()) { |
||||
request.addHeader(e.getKey(), e.getValue()); |
||||
} |
||||
|
||||
if (body != null) { |
||||
request.setEntity(new ByteArrayEntity(body)); |
||||
} |
||||
|
||||
return httpClient.execute(request); |
||||
} |
||||
|
||||
/** |
||||
* Delete |
||||
* |
||||
* @param host |
||||
* @param path |
||||
* @param method |
||||
* @param headers |
||||
* @param querys |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static HttpResponse doDelete(String host, String path, String method, |
||||
Map<String, String> headers, |
||||
Map<String, String> querys) |
||||
throws Exception { |
||||
HttpClient httpClient = wrapClient(host); |
||||
|
||||
HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); |
||||
for (Map.Entry<String, String> e : headers.entrySet()) { |
||||
request.addHeader(e.getKey(), e.getValue()); |
||||
} |
||||
|
||||
return httpClient.execute(request); |
||||
} |
||||
|
||||
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException { |
||||
StringBuilder sbUrl = new StringBuilder(); |
||||
sbUrl.append(host); |
||||
if (!StringUtils.isBlank(path)) { |
||||
sbUrl.append(path); |
||||
} |
||||
if (null != querys) { |
||||
StringBuilder sbQuery = new StringBuilder(); |
||||
for (Map.Entry<String, String> query : querys.entrySet()) { |
||||
if (0 < sbQuery.length()) { |
||||
sbQuery.append("&"); |
||||
} |
||||
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) { |
||||
sbQuery.append(query.getValue()); |
||||
} |
||||
if (!StringUtils.isBlank(query.getKey())) { |
||||
sbQuery.append(query.getKey()); |
||||
if (!StringUtils.isBlank(query.getValue())) { |
||||
sbQuery.append("="); |
||||
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8")); |
||||
} |
||||
} |
||||
} |
||||
if (0 < sbQuery.length()) { |
||||
sbUrl.append("?").append(sbQuery); |
||||
} |
||||
} |
||||
|
||||
return sbUrl.toString(); |
||||
} |
||||
|
||||
private static HttpClient wrapClient(String host) { |
||||
HttpClient httpClient = new DefaultHttpClient(); |
||||
if (host.startsWith("https://")) { |
||||
sslClient(httpClient); |
||||
} |
||||
|
||||
return httpClient; |
||||
} |
||||
|
||||
private static void sslClient(HttpClient httpClient) { |
||||
try { |
||||
SSLContext ctx = SSLContext.getInstance("TLS"); |
||||
X509TrustManager tm = new X509TrustManager() { |
||||
public X509Certificate[] getAcceptedIssuers() { |
||||
return null; |
||||
} |
||||
public void checkClientTrusted(X509Certificate[] xcs, String str) { |
||||
|
||||
} |
||||
public void checkServerTrusted(X509Certificate[] xcs, String str) { |
||||
|
||||
} |
||||
}; |
||||
ctx.init(null, new TrustManager[] { tm }, null); |
||||
SSLSocketFactory ssf = new SSLSocketFactory(ctx); |
||||
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); |
||||
ClientConnectionManager ccm = httpClient.getConnectionManager(); |
||||
SchemeRegistry registry = ccm.getSchemeRegistry(); |
||||
registry.register(new Scheme("https", 443, ssf)); |
||||
} catch (KeyManagementException ex) { |
||||
throw new RuntimeException(ex); |
||||
} catch (NoSuchAlgorithmException ex) { |
||||
throw new RuntimeException(ex); |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue