java 根据图片url识别图片简单实例(百度云通用文字识别)

1.百度云通用文字识别,首先注册百度云账号,创建应用 

2.创建完应用后能够查看自己的

OK, 可以用我写的代码识别图片了

package com.teamdev.jxbrowser.chromium.demo.京东.根据店铺名称搜索商品数据;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.json.JSONObject;

public class getBaiduText {
    private static String api_key="自己的api_key";
    private static String secret_key="自己的secret_key";
    
    //根据图片url识别图片内容
    public static void main(String[] args) {
        String result =getImgText("http://img10.360buyimg.com/imgzone/jfs/t30406/61/230206156/171776/e1bf7570/5bebe2c1N84073dff.jpg");
        System.out.println(result);
    }
    
    //根据图片url识别图片内容
    public static String getImgText(String imgUrl){
            //获取百度云AccessToken
            String accessToken= getAccessToken(api_key,secret_key);
        
            //拼接请求
            String requestUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
            String contentType = "application/x-www-form-urlencoded";  
            String urls = requestUrl + "?access_token=" + accessToken; 
            System.out.println(urls);
            trustEveryone();
            try {  
                URL url = new URL(urls);
                HttpURLConnection con = (HttpURLConnection)url.openConnection();
                con.setRequestMethod("POST");
                con.setDoOutput(true);  
                con.setDoInput(true);
                con.setUseCaches(false);
                // 默认是 GET方式
                 con.setRequestProperty("Content-Type", contentType);
                 con.setRequestProperty("Connection", "Keep-Alive");
                 con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
                OutputStreamWriter out = new OutputStreamWriter(con
                        .getOutputStream(),"utf-8");
                String parm ="url="+imgUrl;
                out.write(new String(parm.getBytes("utf-8")));
                out.flush();
                out.close();
                BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int len;
                byte[] arr = new byte[1024];
                while((len=bis.read(arr))!= -1){
                    bos.write(arr,0,len);
                    bos.flush();
                }
                bos.close();
                return bos.toString("utf-8");
            } catch (MalformedURLException e) {  
                e.printStackTrace();
            } catch (IOException e) {  
                e.printStackTrace();
            }
            return null;
    }
    //获取AccessToken
    public static String getAccessToken(String api_key, String secret_key ){
        String url ="https://aip.baidubce.com/oauth/2.0/token" +
                "?grant_type=client_credentials" +
                "&client_id="+api_key+"&client_secret="+secret_key+"&";
        String result = sendPost(url);
        JSONObject jsonObject = new JSONObject(result);
        String access_token = jsonObject.getString("access_token");
        return access_token;
    }
    
    //ssl协议
    public static void trustEveryone() {
        try {
            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String hostname,
                                SSLSession session) {
                            return true;
                        }
                    });
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context
                    .getSocketFactory());
        } catch (Exception e) {
            
        }
    }
    
    /**
      * 发送post请求
      * */
     public static String sendPost(String urlStr) {  
             trustEveryone();
            try {  
                URL url = new URL(urlStr);
                HttpURLConnection con = (HttpURLConnection)url.openConnection();
                con.setRequestMethod("POST");
                con.setDoOutput(true);  
                con.setDoInput(true);
                con.setUseCaches(false);
                // 默认是 GET方式
//                 con.setRequestProperty("charset", "utf-8");
                 con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
                OutputStreamWriter out = new OutputStreamWriter(con
                        .getOutputStream(),"utf-8");
                String parm ="";
                out.write(new String(parm.getBytes("utf-8")));
                out.flush();
                out.close();
                BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int len;
                byte[] arr = new byte[1024];
                while((len=bis.read(arr))!= -1){
                    bos.write(arr,0,len);
                    bos.flush();
                }
                bos.close();
                return bos.toString("utf-8");
            } catch (MalformedURLException e) {  
                e.printStackTrace();
            } catch (IOException e) {  
                e.printStackTrace();
            }
            return null;  
        }
    
}
 

猜你喜欢

转载自blog.csdn.net/kai402458953/article/details/84649789