百度EasyDL-API接口对接

1、调用前提

  在百度EasyDL中建立数据模型并发布

2、代码

1、测试

package com.stefanie.sun.EasyDLTest;

import com.stefanie.sun.bean.EasyDL.EasydlImageClassify;

/**
 * Created with IntelliJ IDEA
 * StefanieSun
 *
 * @Description:
 * @Author: zy
 * @Date: 2020-06-17 15:53
 * @Version: 1.0.0
 */
public class EasyDLTest {
    public static void main(String[] args) {
        EasydlImageClassify.easydlImageClassify();
    }
}

2、调用

package com.stefanie.sun.bean.EasyDL;

import com.stefanie.sun.util.GsonUtils;
import com.stefanie.sun.util.HttpUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * StefanieSun
 *
 * @Description: 百度EasyDL API接口调用
 * @Author: zy
 * @Date: 2020-06-17 15:48
 * @Version: 1.0.0
 */
public class EasydlImageClassify {

    //检测接口
    private static String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/StefanieSun-NFC";

    // 官网获取的 API Key 更新为你注册的
    private static String clientId = "mYguZCBBruNw6NSQnnLkDc6S";

    // 官网获取的 Secret Key 更新为你注册的
    private static String clientSecret = "OG2YH096CEtQGNGk4KsNwk8qtuVQRZS4";


    /**
     * 上传本地图片进行图像检测
     *
     * @return 检测结果集
     */
    public static String easydlImageClassify() {

        //检测图片转base64格式
        File file = new File("D:\\02 数据文档\\06 API对接文档\\03 测试图\\微信图片_20200617150630.jpg");
        String base64 = ImageBase64.byteConverterBASE64(file);

        try {
            //组装图片信息
            Map<String, Object> map = new HashMap<>();
            map.put("image", base64);
            map.put("top_num", "5");
            String param = GsonUtils.toJson(map);

            //获取token:注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = AuthService.getAuth(clientId, clientSecret);

            //获取返回结果集
            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

3、工具类

package com.stefanie.sun.bean.EasyDL;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * Created with IntelliJ IDEA
 * StefanieSun
 *
 * @Description: 图片转Base64格式
 * @Author: zy
 * @Date: 2020-06-17 16:46
 * @Version: 1.0.0
 */
@Slf4j
public class ImageBase64 {

    public static String byteConverterBASE64(File file) {
        long size = file.length();
        byte[] imageByte = new byte[(int) size];
        FileInputStream fs = null;
        BufferedInputStream bis = null;
        try {
            fs = new FileInputStream(file);
            bis = new BufferedInputStream(fs);
            bis.read(imageByte);
        } catch (FileNotFoundException e) {
            log.error("文件" + file.getName() + "不能被找到:" + e.getMessage());
        } catch (IOException e) {
            log.error("byte转换BASE64出错:" + e.getMessage());
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("关闭输入流出错:" + e.getMessage());
                }
            }
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    log.error("关闭输入流出错:" + e.getMessage());
                }
            }
        }
        return (new sun.misc.BASE64Encoder()).encode(imageByte);
    }

}
package com.stefanie.sun.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

/**
 * Json工具类.
 */
public class GsonUtils {
    private static Gson gson = new GsonBuilder().create();

    public static String toJson(Object value) {
        return gson.toJson(value);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }
}
package com.stefanie.sun.bean.EasyDL;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * StefanieSun
 *
 * @Description: token验证
 * @Author: zy
 * @Date: 2020-06-17 16:29
 * @Version: 1.0.0
 */
public class AuthService {

    // 获取token地址
    private static String authHost = "https://aip.baidubce.com/oauth/2.0/token?";

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     *
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {

        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }

}

package com.stefanie.sun.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
public class HttpUtil {

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }
}

4、pom依赖

    <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

5、导入jar包

链接:https://pan.baidu.com/s/161P6FtgJcILPXS1mxNwUjA
提取码:qz4s

posted @ 2020-06-18 10:21  趙楊  阅读(1420)  评论(1编辑  收藏  举报