调用百度识别(图片识别成文字)

引入依赖

  1. <dependency>
  2. <groupId>org.json</groupId>
  3. <artifactId>json</artifactId>
  4. <version>20171018</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.httpcomponents</groupId>
  8. <artifactId>httpclient</artifactId>
  9. <version>4.5.12</version>
  10. </dependency>

创建类:AuthService

  1. import org.json.JSONObject;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.util.List;
  7. import java.util.Map;
  8. /**
  9. * 获取token类
  10. */
  11. public class AuthService {
  12. /**
  13. * 获取权限token
  14. * @return 返回示例:
  15. * {
  16. * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
  17. * "expires_in": 2592000
  18. * }
  19. */
  20. public static String getAuth() {
  21. // 官网获取的 API Key 更新为你注册的
  22. String clientId = "wcgOtfNCskCzoLqXR1PARIhP";
  23. // 官网获取的 Secret Key 更新为你注册的
  24. String clientSecret = "oxwe4afM0hqGOfnSxp7DCdjvB0yATeVG";
  25. return getAuth(clientId, clientSecret);
  26. }
  27. /**
  28. * 获取API访问token
  29. * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
  30. * @param ak - 百度云官网获取的 API Key
  31. * @param sk - 百度云官网获取的 Securet Key
  32. * @return assess_token 示例:
  33. * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
  34. */
  35. public static String getAuth(String ak, String sk) {
  36. // 获取token地址
  37. String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
  38. String getAccessTokenUrl = authHost
  39. // 1. grant_type为固定参数
  40. + "grant_type=client_credentials"
  41. // 2. 官网获取的 API Key
  42. + "&client_id=" + ak
  43. // 3. 官网获取的 Secret Key
  44. + "&client_secret=" + sk;
  45. try {
  46. URL realUrl = new URL(getAccessTokenUrl);
  47. // 打开和URL之间的连接
  48. HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
  49. connection.setRequestMethod("GET");
  50. connection.connect();
  51. // 获取所有响应头字段
  52. Map<String, List<String>> map = connection.getHeaderFields();
  53. // 遍历所有的响应头字段
  54. for (String key : map.keySet()) {
  55. System.err.println(key + "--->" + map.get(key));
  56. }
  57. // 定义 BufferedReader输入流来读取URL的响应
  58. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  59. String result = "";
  60. String line;
  61. while ((line = in.readLine()) != null) {
  62. result += line;
  63. }
  64. /**
  65. * 返回结果示例
  66. */
  67. System.err.println("result:" + result);
  68. JSONObject jsonObject = new JSONObject(result);
  69. String access_token = jsonObject.getString("access_token");
  70. return access_token;
  71. } catch (Exception e) {
  72. System.err.printf("获取token失败!");
  73. e.printStackTrace(System.err);
  74. }
  75. return null;
  76. }
  77. }

创建类:BaseImg64

  1. import sun.misc.BASE64Encoder;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.URLEncoder;
  6. /**
  7. * 图片转化base64后再UrlEncode结果
  8. */
  9. public class BaseImg64 {
  10. /**
  11. * 将一张本地图片转化成Base64字符串
  12. */
  13. public static String getImageStrFromPath(String imgPath) {
  14. InputStream in;
  15. byte[] data = null;
  16. // 读取图片字节数组
  17. try {
  18. in = new FileInputStream(imgPath);
  19. data = new byte[in.available()];
  20. in.read(data);
  21. in.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. // 对字节数组Base64编码
  26. BASE64Encoder encoder = new BASE64Encoder();
  27. // 返回Base64编码过再URLEncode的字节数组字符串
  28. return URLEncoder.encode(encoder.encode(data));
  29. }
  30. }

创建类:Check

  1. import org.apache.http.HttpResponse;
  2. import org.apache.http.client.HttpClient;
  3. import org.apache.http.client.methods.HttpPost;
  4. import org.apache.http.entity.StringEntity;
  5. import org.apache.http.impl.client.DefaultHttpClient;
  6. import org.apache.http.util.EntityUtils;
  7. import java.io.File;
  8. import java.io.IOException;
  9. import java.net.URI;
  10. import java.net.URISyntaxException;
  11. /**
  12. * 图像文字识别
  13. */
  14. public class Check {
  15. private static final String POST_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + AuthService.getAuth();
  16. /**
  17. * 识别本地图片的文字
  18. */
  19. public static String checkFile(String path) throws URISyntaxException, IOException {
  20. File file = new File(path);
  21. if (!file.exists()) {
  22. throw new NullPointerException("图片不存在");
  23. }
  24. String image = BaseImg64.getImageStrFromPath(path);
  25. String param = "image=" + image;
  26. return post(param);
  27. }
  28. /**
  29. * 图片url
  30. * 识别结果,为json格式
  31. */
  32. public static String checkUrl(String url) throws IOException, URISyntaxException {
  33. String param = "url=" + url;
  34. return post(param);
  35. }
  36. /**
  37. * 通过传递参数:url和image进行文字识别
  38. */
  39. private static String post(String param) throws URISyntaxException, IOException {
  40. //开始搭建post请求
  41. HttpClient httpClient = new DefaultHttpClient();
  42. HttpPost post = new HttpPost();
  43. URI url = new URI(POST_URL);
  44. post.setURI(url);
  45. //设置请求头,请求头必须为application/x-www-form-urlencoded,因为是传递一个很长的字符串,不能分段发送
  46. post.setHeader("Content-Type", "application/x-www-form-urlencoded");
  47. StringEntity entity = new StringEntity(param);
  48. post.setEntity(entity);
  49. HttpResponse response = httpClient.execute(post);
  50. // System.out.println(response.toString());
  51. if (response.getStatusLine().getStatusCode() == 200) {
  52. String str;
  53. try {
  54. //读取服务器返回过来的json字符串数据
  55. str = EntityUtils.toString(response.getEntity());
  56. System.out.println(str);
  57. return str;
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. return null;
  61. }
  62. }
  63. return null;
  64. }
  65. public static void main(String[] args) {
  66. String path = "/Users/keliang/Desktop/data/name.jpeg";
  67. try {
  68. long now = System.currentTimeMillis();
  69. checkFile(path);
  70. System.out.println("耗时:" + (System.currentTimeMillis() - now) / 1000 + "s");
  71. } catch (URISyntaxException | IOException e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. }