import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
String filePath = "image.jpg";
URL realUrl = new URL("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=your_access_token");
HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
String body = String.format("id_card_side=front&image=%s", URLEncoder.encode(new BASE64Encoder().encode(readImage(filePath)).replaceAll("\r|\n", "")));
connection.getOutputStream().write(body.getBytes("UTF-8"));
connection.connect();
System.out.println(
new BufferedReader(new InputStreamReader(connection.getInputStream())).readLine()
);
}
public static byte[] readImage(String filePath){
File file = new File(filePath);
byte[] content = new byte[new Long(file.length()).intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(content);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
问题注意事项:
1. sun.misc.BASE64Encoder返回的编码含有换行回车,请使用.replaceAll("\r|\n", "")将其替换,否则无法识别。
2. HTTP body 里面参数值一定要经过URLEncoder.encode,否则无法识别。
对于新手可以参考
感谢大神总结经验啊
感谢分享,大家可参考哦