第一步,Token的获取
String client_id = accessToken.getClient_id();
String grant_type = accessToken.getGrant_type();
String client_secret = accessToken.getClient_secret();
String url = "https://aip.baidubce.com/oauth/2.0/token?"+
"grant_type=client_credentials"+
"&client_id="+client_id
+"&client_secret="+client_secret;
try {
URL getTokenUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) getTokenUrl.openConnection();
connection.setRequestMethod("POST");
connection.connect();
Map<String, List<String>> map2 = connection.getHeaderFields();
for (String key : map2.keySet()) {
System.err.println(key + "--->" + map2.get(key));
}
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 = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
首先定义获取token的字段,然后是地址,打开链接,选择发送方法为POST方法,然后开始链接
,最后通过BufferedReader 获取响应流,再用流的读取即可获取获得的数据,最后转化成Json格式,再将数据转成String即可。
然后是OCR文字识别的接口调用
String filePath = "D:\\QQ截图20220728144503.png";
String urlpath1 = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
String encoding = "UTF-8";
if (urlpath1.contains("nlp")) {
encoding = "GBK";
}
String Result = "";
try {
byte[] imgbyte = FileUtil.readFileByBytes(filePath);
String encodeimg = Base64Util.encode(imgbyte);
String urlencode = URLEncoder.encode(encodeimg,"UTF-8");
String accesstoken="24.9a9540cf55ce1b7c47a9e3f4504c60f0.2592000.1661591980.282335-26826072";
String urlpaths=urlpath1+"?access_token=" + accesstoken;
String contentType = "application/x-www-form-urlencoded";
String param = "image="+urlencode;
URL urlpath = new URL(urlpaths);
HttpURLConnection connection = (HttpURLConnection)urlpath.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(param.getBytes(encoding));
out.flush();
out.close();
connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while((line = bufferedReader.readLine()) !=null){
Result+=line;
}
bufferedReader.close();
JSON json = (JSON) JSON.parse(Result);
String result = json.toJSONString(json);
System.out.println(result);
return result;
调用OCR文字识别的接口有几个要求,URL地址内要放入AccessToken
,Header内要放入
Content-Type | application/x-www-form-urlencoded |
Body中放置参数
也就是图片
放置在Body内的内容用
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
然后通过out.write(param.getBytes(encoding));
传输即可
当然发送http请求可以通过工具包简化操作,无需这么复杂。