@Override public Tag recognize(String image, String token) throws IOException { //判断参数为空 //image为图片转BASE64码后的数据 if (StringUtils.isBlank(image)) { logger.info("image is empty!"); throw new BadParamException("image is empty!"); } File file = null; BufferedOutputStream bos = null; java.io.FileOutputStream fos = null; token = serverConfig.get("recognizeToken"); String filePath = serverConfig.get("documentPath") + "image"; logger.info(image); File dir = new File(filePath); if (!dir.exists() && !dir.isDirectory()) { dir.mkdirs(); } byte[] bytes = new BASE64Decoder().decodeBuffer(image); String path = filePath + "\\" + "person.png"; file = new File(filePath + "\\" + "person.png"); fos = new java.io.FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(bytes); bos.close(); String url = serverConfig.get("faceServerAddress"); String responseStr = sendGetFile(url, path, token); logger.info(responseStr); if (responseStr == null) { throw new BadParamException("人脸识别接口异常"); } PersonImageInfo response = GsonUtils.fromJson(responseStr.toLowerCase(), PersonImageInfo.class); logger.info(response); if (response.getPerson() == null) { logger.info("人脸识别失败:" + response.getError()); throw new BadParamException("识别分数过低"); } net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(response.getPerson().getTag()); //String c=jsonObj.getString("job_number"); Iterator iterator = jsonObj.keys(); Tag tag = new Tag(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = jsonObj.getString(key); if (key.equals("job_number")) { tag.setJobNumber(value); logger.info(value); return buildTag(tag); } } return null; } //get请求 public static String sendGetFile(String url, String filePath, String token) { String sResponse = ""; try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); File file = new File(filePath); FileBody bin = new FileBody(file); StringBody comment = new StringBody(token, ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("image", bin) .addPart("screen_token", comment) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpClient.execute(httppost); HttpEntity resEntity = response.getEntity(); sResponse = EntityUtils.toString(resEntity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return sResponse; }
调用别人接口并返回参数
最新推荐文章于 2022-07-28 10:04:58 发布