java -- 百度API 接口使用
百度API 控制台地址: https://console.bce.baidu.com/?fromai=1#/aip/overview
创建应用后获得 API Key – Secret Key
maven 依赖
普通项目去maven中央仓库根据groupId 搜索下载 jar 包
<!--百度文字识别接口 sdk --><dependency><groupId>com.baidu.aip</groupId><artifactId>java-sdk</artifactId><version>4.5.0</version></dependency><!-- httpcore --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId></dependency><!-- httpclient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><!-- jsonObject 支持 --><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency>
token 获取方法(需先创建应用)
package com.example.demo;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;import net.sf.json.JSONObject;/*** 获取token类*/
public class AuthService {/*** 官网获取的 API Key 更新为你注册的*/static String clientId = "YvWmx5eHYExqwI76606MsExd";/*** 官网获取的 Secret Key 更新为你注册的*/static String clientSecret = "Re93cqHB7ElIzSzTZnO4bOUsGmNvKm4Q";/*** token 到期时间*/public static long tokenTime = 0L;/*** token*/public static String access_token;/*** 判断是否过期-获取token* * @author wangsong* @date 2019年6月29日 上午10:17:43* @return*/public static String getToken() {if (System.currentTimeMillis() > tokenTime) {getAuth();}return access_token;}/*** 获取权限token, 获取API访问token 该token有一定的有效期,需要自行管理,当失效时需重新获取.* * @return 返回示例: { "access_token":* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",* "expires_in": 2592000 }*/public static void getAuth() {// 获取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=" + clientId// 3. 官网获取的 Secret Key+ "&client_secret=" + clientSecret;try {URL realUrl = new URL(getAccessTokenUrl);// 打开和URL之间的连接HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();connection.setRequestMethod("POST");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 = JSONObject.fromObject(result);String expires_in = jsonObject.getString("expires_in");// tokenaccess_token = jsonObject.getString("access_token");// 过期时间tokenTime = System.currentTimeMillis() + Long.valueOf(expires_in);} catch (Exception e) {System.err.printf("获取token失败!");e.printStackTrace(System.err);}}/*** 获取测试* * @author wangsong* @date 2019年6月29日 上午10:18:57* @param args*/public static void main(String[] args) {String auth = getToken();System.out.println(auth);}
}
1、 网络图片文字识别
创建应用,获取 key
java 代码
base64 工具类
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;import sun.misc.BASE64Encoder;/*** 图片转化base64后再UrlEncode结果*/@SuppressWarnings("all")
public class BaseImg64 {/*** 将一张本地图片转化成Base64字符串*/public static String getImageStrFromPath(String imgPath) {InputStream in;byte[] data = null;// 读取图片字节数组try {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编码过再URLEncode的字节数组字符串return URLEncoder.encode(encoder.encode(data));}
}
调用网络图片文字识别 api 接口
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;/*** 百度图片识别api接口* * @author wangsong* @date 2019年6月28日 下午7:43:49*/
@SuppressWarnings("all")
public class BaiduImgApi {/*** 图像文字识别*/private static final String POST_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+ AuthService.getToken();/*** 识别本地图片的文字*/public static String checkFile(String path) throws URISyntaxException, IOException {File file = new File(path);if (!file.exists()) {throw new NullPointerException("图片不存在");}String image = BaseImg64.getImageStrFromPath(path);String param = "image=" + image;return post(param);}/*** 图片url 识别结果,为json格式*/public static String checkUrl(String url) throws IOException, URISyntaxException {String param = "url=" + url;return post(param);}/*** 通过传递参数:url和image进行文字识别*/private static String post(String param) throws URISyntaxException, IOException {// 开始搭建post请求HttpClient httpClient = new DefaultHttpClient();HttpPost post = new HttpPost();URI url = new URI(POST_URL);post.setURI(url);// 设置请求头,请求头必须为application/x-www-form-urlencoded,因为是传递一个很长的字符串,不能分段发送post.setHeader("Content-Type", "application/x-www-form-urlencoded");StringEntity entity = new StringEntity(param);post.setEntity(entity);HttpResponse response = httpClient.execute(post);System.out.println(response.toString());if (response.getStatusLine().getStatusCode() == 200) {String str;try {// 读取服务器返回过来的json字符串数据str = EntityUtils.toString(response.getEntity());System.out.println(str);return str;} catch (Exception e) {e.printStackTrace();return null;}}return null;}/*** 测试* * @author wangsong* @date 2019年6月29日 上午10:58:17* @param args*/public static void main(String[] args) {String path = "D:\\test.png";try {long now = System.currentTimeMillis();checkFile(path);System.out.println("耗时:" + (System.currentTimeMillis() - now) / 1000 + "s");} catch (URISyntaxException | IOException e) {e.printStackTrace();}}
}
java -- 百度API 接口使用相关推荐
- java 百度api接口开发_百度熊掌号使用Java工具类对接API推送接口进行文章推送实例详解...
对于java程序员来说,自己运维的百度熊掌号当然得使用java的方式去每天推送文章了.目前,百度推出了百度熊掌号服务.旨在更好的为站长服务.那么百度熊掌号如何通过推送API接口实现自动文章推送呢? 第 ...
- java 百度api接口开发_百度CFC Java免费 接口
以前只有 nodejs ,后来 新增了python2,今天突然发现支持 Java了 目前nodejs,python2 都有模板,j ava 没有模板 感觉也不需要 百度云CFC 目前 免费,在 ...
- java 百度api人脸识别功能(人脸识别+详细案例+接口及所需工具类)
最近开发过程中需要用到人脸识别认证功能,然后就用的是百度API接口进行开发,起初设想用直接用人脸识别还是用注册到百度人脸库识别两种方法,为了简化开发直接就用了第一种方式: 直接上业务逻辑代码吧: po ...
- 基于百度api接口的车辆识别计费系统
又是一年毕业季,前段时间帮学弟指导了一个车辆识别计费系统,整个的实现思路在此记录下,感兴趣的可以参考一下. 整个项目沟通后情况如下: 需求功能: 1.住户的登记,小区.手机号码.姓名.地址: 2.访客 ...
- 五十一、结合百度API接口打造 Python小项目
@Author: Runsen 本项目围绕图像识别,通过调用百度 API 接口,可以实现很多人性化的功能,比如手势识别.比对.人像分割以及颜值打分等功能. 本次Gitchat付费文章,但是因为订阅太少 ...
- JS调用百度api接口——实现简单的百度页面
描述: JS调用百度api接口--实现简单的百度页面 效果: 实现: css文件: @charset "utf-8"; /* CSS Document */ *{margin: 0 ...
- java 地图api接口_Java调用百度地图API
本实战代码将使用百度地图的接口来实现以下功能: 1.确定输入地址的坐标 2.两个坐标的距离 其他的话,还要使用百度账户申请相关的api,具体见: http://lbsyun.baidu.com/ind ...
- java百度天气接口解析_Java调用天气接口(百度天气)解析返回的JSON数据
简介:本文详细讲述了通过Java调用百度天气接口的方法,取得返回的JSON格式的数据,并且通过第三方包解析JSON格式的数据. 通过百度天气API调用网络编程接口接收返回的JSON格式的数据. 关于百 ...
- python卷java实现api接口提供(一)
前言 前段时间分享了一个Django项目跑起来的基本操作,现在回过头来,我们来一场python的Django项目从无到有. python环境这里就不说了,自行百度. 一.编辑工具与插件 开发工具:py ...
- 我也没想到,Java开发 API接口可以不用写 Controller了
大家好,我是小富~ 今天介绍我正在用的一款高效敏捷开发工具magic-api,顺便分享一点工作中使用它的心得 缘起 先说一下我为什么会使用这个工具? 最近新启动一个项目,业务并不算复杂,那种典型的管理 ...
最新文章
- Android_微信_设置
- 时间稍纵即逝,好久不见~ [QQ群均已解散,暂只保留UE4群]
- adsl服务器客户端配置cisco_基于ISE对Cisco网络设备部署AAA
- 亚马逊AWS 数据中心起火,致 5 人死亡、50 人受伤
- 【期外】 (一)关于LSH :局部敏感哈希算法
- 万万没想到,AI算法开发、OCR应用已经进入零门槛时代!
- 在Linux下生成crypt加密密码
- 百度回应“宕机”;微信 5 年内出 VR 版?腾讯破解谷歌漏洞 | 极客头条
- Vue子组件调用父组件的方法
- ARC_x86_OS选择
- 计算机应用技术和it有什么区别,IT是程序员吗?IT究竟是什么意思?
- 友盟php接入统计,Android应用中添加友盟统计_PHP教程
- [BZOJ1984]月下“毛景树”(树链剖分)
- repost 编程之路--一个程序员的艰辛经历
- c 语言编程 脚本之家,wincc c脚本实例wincc赋值程序
- tomcat下载和配置(简单,详细)
- MyBatis映射文件如何给数据库的int类型字段“插入”string类型记录
- Linux学习日志_虚拟化管理工具
- matlab网络通讯消息响应,nevoVI FIRE——实现PC与CAN和LIN网络通信
- 在Mac下安装XAMPP