百度API连接

百度API连接分为两步:

1、使用API key和secret key获取token

2、连接调用方法。


1、获取token。

 public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "XP8YaCKuqZW7GIfEf05iFa";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "jrFmEH4VX9MsSUaEFm7LH0tGZt1B7";
        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?grant_type=client_credentials";
        String getAccessTokenUrl = authHost+ "&client_id=" + ak + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

2、连接:识别图片中的文字

public static void main(String[] args) {
		File file = new File("d:/test.jpg");  
        String imageBase = encodeImgageToBase64(file);
        
        imageBase = imageBase.replaceAll("\r\n","");  
        imageBase = imageBase.replaceAll("\\+","%2B");  
        
        String httpUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=24.6cc81615b0f0940b002f39bb3ee08.2592000.1519375458.282335-10719029";  
        String httpArg = "image="+imageBase;  
        String res = request(httpUrl, httpArg);
	}
	
	public static String request(String httpUrl, String httpArg) {  
        BufferedReader reader = null;  
        StringBuffer sbf = new StringBuffer();  
        try {  
            URL url = new URL(httpUrl);  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
            connection.setRequestMethod("POST");  
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
            connection.setDoOutput(true);  
            connection.getOutputStream().write(httpArg.getBytes("UTF-8")); 
            connection.connect();  
            InputStream is = connection.getInputStream();  
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));  
            String strRead = null;  
            while ((strRead = reader.readLine()) != null) {
        		sbf.append(strRead);  
        		sbf.append("\r\n");  
            }  
            reader.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return sbf.toString();  
    }  
	
	
	public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理  
	    // 其进行Base64编码处理  
	    byte[] data = null;  
	    // 读取图片字节数组  
	    try {  
	        InputStream in = new FileInputStream(imageFile);  
	        data = new byte[in.available()];  
	        in.read(data);  
	        in.close();  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    }  
	    // 对字节数组Base64编码  
	    return  new BASE64Encoder().encode(data);// 返回Base64编码过的字节数组字符串  
	} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值