身份证识别通过RestTemple进行的post请求。

通过RestTemple进行的post请求。其中的参数是file类型,
工具 idea 项目 mevan 技术 sringboot


```java
package com.guangda.CardApply;

import com.guangda.untils.HttpsClientRequestFactory;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * 身份证orc验证
 * 前台传递,照片。
 */
@RestController
public class SFZIdcardApply {
    @Autowired
    RestTemplate restTemplate;

    @RequestMapping(value = "/idcard/SFZapply", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject idcardApply(@RequestParam("myFile") MultipartFile myFile,String fileCategory) throws IOException {
//    public JSONObject idcardApply() throws MalformedURLException {
        if (Objects.isNull(myFile) || myFile.isEmpty()) {//判断非空
            // logger.error("文件为空");
            return null;
        }
        //第三方地址
        String url=" https:";
        //必须转换一下,否则请求的时候会报错
        URL url1=new URL(url);
        //第三方要求的参数
        boolean formSdk=false;
        Set tempFilePath = new HashSet<>();
        //第三方接口生成的token
        String token=new ThirdApply().apply().getJSONObject("data").get("token").toString();
        RestTemplate template = new RestTemplate(new HttpsClientRequestFactory());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap params = new LinkedMultiValueMap<>();
        if (null != myFile && !myFile.isEmpty()) {
            //生成临时的文件,完成传输后再删除
            File tempFile = new File( UUID.randomUUID().toString()+myFile.getOriginalFilename());
            tempFilePath.add(tempFile.getAbsolutePath());
            FileUtils.copyInputStreamToFile(myFile.getInputStream(), tempFile);
            FileSystemResource fileSystemResource = new FileSystemResource(tempFile);
            params.add("fileData", fileSystemResource);
        }
        params.add("formSdk", formSdk);
        params.add("fileCategory", fileCategory);
        params.add("token", token);
        HttpEntity> requestEntity = new HttpEntity>(params,headers);
        ResponseEntity response = template.postForEntity(url1.toString(), requestEntity, JSONObject.class);
        return response.getBody();
    }
}

你可能感兴趣的:(代码,java)