天天看点

使用httpclient调用百度接口进行车辆损伤图片识别

最近,项目中,需要百度的接口对车辆外观损伤的信息进行识别。之前没做过这方面相关的,现做一个demo来学习实现一下

一、首先我们先浏览一下百度api文档,里面有相关的接口介绍~(https://ai.baidu.com/docs#/ImageClassify-API/b80093c8)

使用httpclient调用百度接口进行车辆损伤图片识别

二、根据文档我们知道,在调用图片识别接口的时候需要先获取access_token,文档里面也提供了我们获取token的方式,稍作修改如下

package com.ljm.demo;

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;

/**
 * 获取token类
 */
public class AuthService {

    /**
     * 获取权限token
     * @return 返回示例:
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "uIHAhDByPdCG10O1111111";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "9V9yfT1MmYboTTW111111";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取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) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        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;
    }

    public static void main(String[] args) {
        System.out.println(getAuth());

    }
}
           

上述的ApiKey和SecretKey可登陆百度控制台查看,第一次登陆需要创建应用:

使用httpclient调用百度接口进行车辆损伤图片识别
使用httpclient调用百度接口进行车辆损伤图片识别

三、执行代码获取access_token之后,使用http请求调用百度图像识别接口

package com.ljm.demo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;

/**
 * Created by linjiaming
 */

public class BaiduAiTest {

    public static void main(String[] args) {
        getBaiduAiResult();
    }

    public static void getBaiduAiResult() {
        try {
            String accessToken = "生成的token";
            String postURL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/vehicle_damage"
                    + "?access_token=" + accessToken;
            //System.out.println(postURL);
            //http的 cookie 的 path 属性不一致,cookie中的是"baidu.com",而请求路径path中的是"aip.baidubce.com".
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec("aip.baidubce.com").build();
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

            HttpPost httpPost = new HttpPost(postURL);
            httpPost.setHeader("Content-Type",
                    "application/x-www-form-urlencoded;charset=utf-8");
            List<NameValuePair> params=new ArrayList<>();
           
            params.add(new BasicNameValuePair("image", ImageToBase64("D:\\test.jpg")));

            String str= EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

            // 获取结果实体
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                //进行输出操作 这里就简单的使用EntityUtils工具类的toString()方法
                System.out.println(EntityUtils.toString(entity,"UTF-8"));
            }
            else {
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        //System.out.println("本地图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
        return encoder.encode(Objects.requireNonNull(data));
    }
}
           

测试图片:

使用httpclient调用百度接口进行车辆损伤图片识别

测试结果:

{
	"log_id": 7151095137225675373,
	"result": {
		"damage_info": [{
			"parts": "后保险杠",
			"type": "刮擦",
			"probability": 89
		}, {
			"parts": "右后叶子板",
			"type": "刮擦",
			"probability": 47
		}]
	}
}
           

继续阅读