java--百度图片审核 image format error解决

图像审核API参考

文档地址

https://cloud.baidu.com/doc/ANTIPORN/s/jk42xep4e

注意
Content-Type为application/x-www-form-urlencoded,然后通过urlencode格式化请求体。

代码

1.图片转base64

注意使用java.util.Base64的包,生成的base64才不会带换行符

    import java.util.Base64;
    
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小(字节Byte)=" + in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码,得到Base64编码的字符串
        return new String(Base64.getEncoder().encodeToString(data));
    }

2.发送POST请求

    /**
     * 向指定URL发送POST方法的请求 Content-Type=application/x-www-form-urlencoded
     *
     * @param targetUrl 发送请求的URL
     * @param params    请求参数,请求参数应该是name1=value1&name2=value2的形式。
     * @return JSONObject 返回的JSON数据
     */
    public static JSONObject postFormUrlEncoded(String targetUrl, String params) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(targetUrl.trim());
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            // 百度要求此类型上传图片
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);

            urlConnection.connect();
            PrintWriter out = new PrintWriter(new OutputStreamWriter(urlConnection.getOutputStream(), StandardCharsets.UTF_8));
            // 写入参数
            out.print(params);
            out.flush();

            int resultCode = urlConnection.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                StringBuffer stringBuffer = new StringBuffer();
                String readLine;
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
                while ((readLine = responseReader.readLine()) != null) {
                    stringBuffer.append(readLine);
                }
                responseReader.close();
                return JSONObject.parseObject(stringBuffer.toString());
            }
            out.close();
        } catch (Exception e) {
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }

3.图片审核

    /**
     * 获得校验结果
     *
     * @param imgBase64 Base64格式
     * @param imgType   0 静态图片 1 动态图片
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Boolean getCensorResult(String imgBase64, String imgType) {

        if (ValidatorUtils.isEmpty(accessToken)) {
            getAccessToken();
        }

        try {
            String params = "image=" + URLEncoder.encode(imgBase64,"UTF-8") + "&imgType=" + imgType + "&access_token=" + accessToken;
            JSONObject jsonObject;
            //post 请求方式
            jsonObject = HttpUtils.postFormUrlEncoded(host, params);
            if (jsonObject.get("error_code") != null) {
                // token失效
                if ("110".equals(jsonObject.get("error_code"))) {
                    getAccessToken();
                }
                System.out.println(" 校验失败,原因:" + jsonObject.get("error_msg"));
                return false;
            }
            if ("1".equals(jsonObject.get("conclusionType").toString())) {
                return true;
            } else {
                System.out.println(" 校验失败,原因:" + jsonObject.get("data"));
                return false;
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            return false;
        }
    }

踩坑

通过第一段代码的返回的base64图片格式需要使用URLEncoder格式化一遍,否则会报错

String params = "image=" + URLEncoder.encode(imgBase64,"UTF-8") + "&imgType=" + imgType + "&access_token=" + accessToken;

错误的写法

String params = "image=" + imgBase64 + "&imgType=" + imgType + "&access_token=" + accessToken;
上一篇:java实现下载器(以及创建一个URL对象)


下一篇:http(S)系列之(五):android之Http(s)URLConnection(6):流程图