httpclient案例一(调用识别接口)

时间:2022-11-26 20:05:30
 public Map<String, Object> pictureRecognition(String recotype, MultipartFile imageFile) {
         String result = null;
         // 文件输入流
         FileInputStream fs = null;
         try {
             String configValue = cpConfigService.getValueByConfigKey("ocr_server_config", "{'uri':'http://cloud.exocr.com/recognize','username':'test','password':'test'}");
             Map<String, String> configMap = JsonUtils.json2Map2(configValue);
             String postUrl = configMap.get("uri"); // 服务地址
             Map<String, String> postParam = new HashMap<String, String>(10);
             postParam.put("username", configMap.get("username")); // 用户名, 公有云测试可使用’test’
             postParam.put("password", configMap.get("password")); // 密码,公有云测试可使用 ’test’
             postParam.put("recotype", recotype); // BankCard
             postParam.put("encoding", "utf-8"); // 返回结果的文字编码方式,取值包括:utf-8, 默认值 gb2312
             postParam.put("head_portrait", "0"); // 是否返回头像(base64格式),只对身份证识别有效,取值范围:0,默认,不返回头像    1,则返回身份证的头像照片
             postParam.put("crop_image", "0"); // 是否返回切边(base64格式),取值:0,    默认,不返回切边图    1,    返回切边图
             postParam.put("b64", "1"); // 输入图片是否为base64格式,取值:0,    默认,二进制格式   1,    base64格式
             // base64编码图像
             String base64 = new String(Base64.encodeBase64(imageFile.getBytes()));
             postParam.put("image", base64); // 待识别的图像,可以是二进制也可以是base64格式
             result = HttpUtil.postUrlAsString(postUrl, postParam, null, "utf-8");
             logger.info("OCR识别结果{}", result);
         } catch (Exception e) {
             logger.error("OCR识别异常:", e);
             StringBuilder sb = new StringBuilder();
             sb.append("{'Error':'99','Details':'OCR识别异常:");
             sb.append(e.getMessage()).append("'}");
             result = sb.toString();
         } finally {
             if (null != fs) {
                 try {
                     fs.close();
                 } catch (IOException e) {
                     logger.error("File input stream close exception:", e);
                 }
             }
         }

         try {
             return JsonUtils.json2Map(result);
         } catch (Exception e) {
             logger.error("json to map exception:", e);
         }

         return null;
     }
   public static String postUrlAsString(String url,
             Map<String, String> params, Map<String, String> reqHeader,
             String encode) throws Exception {
         // 开始时间
         long t1 = System.currentTimeMillis();
         // 获得HttpPost对象
         HttpPost httpPost = getHttpPost(url, params, encode);
         // 发送请求
         String result = executeHttpRequest(httpPost, reqHeader, encode);
         // 结束时间
         long t2 = System.currentTimeMillis();
         // 调试信息
         logger.debug("url:" + url);
         logger.debug("params:" + params.toString());
         logger.debug("reqHeader:" + reqHeader);
         logger.debug("encode:" + encode);
         logger.debug("result:" + result);
         logger.debug("consume time:" + ((t2 - t1)));
         // 返回结果
         return result;
     }  
   private static HttpPost getHttpPost(String url, Map<String, String> params,
             String encode) throws UnsupportedEncodingException {
         HttpPost httpPost = new HttpPost(url);
         if (params != null) {
             List<NameValuePair> form = new ArrayList<NameValuePair>();
             for (String name : params.keySet()) {
                 form.add(new BasicNameValuePair(name, params.get(name)));
             }

             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,
                     encode);
             httpPost.setEntity(entity);
         }

         return httpPost;
     }  
  /**
      * 执行HTTP请求
      *
      * @param request
      *            请求对象
      * @param reqHeader
      *            请求头信息
      * @return 内容字符串
      */
     private static String executeHttpRequest(HttpUriRequest request,
             Map<String, String> reqHeader, String encode) throws Exception {
         HttpClient client = null;
         String result = null;
         try {
             // 创建HttpClient对象
             client = new DefaultHttpClient();
             // 设置连接超时时间
             client.getParams().setParameter(
                     CoreConnectionPNames.CONNECTION_TIMEOUT, 60);
             // 设置Socket超时时间
             client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                     36600);
             // 设置请求头信息
             if (reqHeader != null) {
                 for (String name : reqHeader.keySet()) {
                     request.addHeader(name, reqHeader.get(name));
                 }
             }
             // 获得返回结果
             HttpResponse response = client.execute(request);
             // 如果成功
             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                 encode = StringUtils.isNotEmpty(encode) ? encode : DEFAULT_ENCODE;
                 result = EntityUtils.toString(response.getEntity(), encode);
             } else {
                 StringBuffer errorMsg = new StringBuffer();
                 errorMsg.append("httpStatus:");
                 errorMsg.append(response.getStatusLine().getStatusCode());
                 errorMsg.append(response.getStatusLine().getReasonPhrase());
                 errorMsg.append(", Header: ");
                 Header[] headers = response.getAllHeaders();
                 for (Header header : headers) {
                     errorMsg.append(header.getName());
                     errorMsg.append(":");
                     errorMsg.append(header.getValue());
                 }
                 logger.error("HttpResonse Error:" + errorMsg);
                 result = "{'Error':'98','Details':'" + errorMsg.toString() + "'}";
             }
         } catch (Exception e) {
             logger.error("http连接异常", e);
             throw new Exception("http连接异常");
         } finally {
             try {
                 client.getConnectionManager().shutdown();
             } catch (Exception e) {
                 logger.error("finally HttpClient shutdown error", e);
             }
         }
         return result;
     }