百度通用OCR文字识别 Http方式请求

2019-09-27  本文已影响0人  yasuion

1:获取token

private void getToken() {

// 官网获取的 API Key 更新为你注册的

    String clientId ="你的ak";

// 官网获取的 Secret Key 更新为你注册的

    String clientSecret ="你的sk";

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;

OkGo.get(getAccessTokenUrl)

.execute(new StringCallback() {

@Override

                public void onSuccess(Response response) {

JSONObject jsonObject =null;

try {

jsonObject =new JSONObject(response.body());

String access_token = jsonObject.getString("access_token");

Message message=Message.obtain();

message.what=0;

message.obj=access_token;

mHandler.sendMessage(message);

}catch (JSONException e) {

e.printStackTrace();

}

}

});

}

// handler

private String token;

@SuppressLint("HandlerLeak")

private HandlermHandler=new Handler() {

@Override

    public void handleMessage(Message msg) {

super.handleMessage(msg);

switch (msg.what){

case 0:

token= (String) msg.obj;

scanImg();

break;

}

}

};

//注意token过期然后重新获取 这里是测试代码 没有搞这一步(大概就是把token保存下来 请求识别的接口时判断token的状态 过期了就重新获取token)

2:识别

private String url="https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";

private Bitmap bitmap;

private void scanImg() {

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);// 自己找张图片放进去

String bitmapToBase64 =bitmapToBase64(bitmap);

OkGo.post(url+"?access_token="+token)

.tag(this)

.headers("Content-Type","application/x-www-form-urlencoded")

.params("image",bitmapToBase64)

.params("language_type","CHN_ENG")

.params("detect_direction",false)

.params("detect_language",false)

.params("probability",false)

.execute(new StringCallback() {

@Override

                public void onSuccess(Response response) {

Log.d("wangwu","onSuccess: "+response.body().toString());

}

});

}

/*

* bitmap转base64

* */

private static String bitmapToBase64(Bitmap bitmap) {

String result =null;

ByteArrayOutputStream baos =null;

try {

if (bitmap !=null) {

baos =new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG,100, baos);

baos.flush();

baos.close();

byte[] bitmapBytes = baos.toByteArray();

result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);

}

}catch (IOException e) {

e.printStackTrace();

}finally {

try {

if (baos !=null) {

baos.flush();

baos.close();

}

}catch (IOException e) {

e.printStackTrace();

}

}

return result;

}

注意:

"error_code": 216101

请求接口的时候用post不要用get!

// 百度文字识别错误码连接:

https://cloud.baidu.com/doc/OCR/s/zjwvxzrw8/

上一篇下一篇

猜你喜欢

热点阅读