准备工作:在libs下添加 alicloud-Android-apigateway-sdk-1.0.1.jar,commons-codec-1.10-1.jar
在build.gradle添加 compile'com.squareup.okhttp3:okhttp:3.4.1'
在onCreate,或者afterViews初始化API网关
private void initGatewaySdk() { // 初始化API网关 ApiGatewayClient.init(getApplicationContext(), false); }
调用拍照功能
private void getPhotoCard(){ final String status = Environment.getExternalStorageState(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_REQUEST_CODE); } if (status.equals(Environment.MEDIA_MOUNTED)) { defaultPhotoAddress = PHOTO_DIR + "/" + getPhotoName(); PreferenceUtils.modifyStringValueInPreferences(CardActivity.this, Preferences.IMAGE_3, defaultPhotoAddress); imageUri = Uri.fromFile(new File(defaultPhotoAddress)); Intent intentPhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intentPhoto, CAMERA_REQUEST_CODE); } else { Toast.makeText(CardActivity.this, "没有sd卡", Toast.LENGTH_SHORT).show(); } }
可以对照片进行裁剪
private void cropImageUri(Uri desUri, int outputX, int outputY, int requestCode){ Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(desUri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 5); intent.putExtra("aspectY", 3); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, desUri); intent.putExtra("return-data", false); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); startActivityForResult(intent, requestCode); }
用base64上传照片
private void trygetCardNum() { if (NetworkUtils.isConnectWithTip(this, "您未连接网络,无法获取数据")) { LoadingUtil.show(this); String imgBase64 = ""; try { defaultPhotoAddress = PreferenceUtils.getStringValueInPreferences(this, Preferences.IMAGE_3); File file = new File(defaultPhotoAddress); byte[] content = new byte[(int) file.length()]; FileInputStream finputstream = new FileInputStream(file); finputstream.read(content); finputstream.close(); imgBase64 = new String(Base64.encodeBase64(content)); // imgBase64 = Base64Img.Bitmap2StrByBase64(bitmap); if(imgBase64!=null||!imgBase64.equals("")){ PreferenceUtils.modifyStringValueInPreferences(CardActivity.this, Preferences.IMAGE_3, null); } } catch (IOException e) { e.printStackTrace(); return; } // 获取服务 RpcService rpcService = ApiGatewayClient.getRpcService(); final ApiRequest apiRequest = new ApiRequest(); // 设置请求地址、Path及Method apiRequest.setAddress("https://dm-51.data.aliyun.com"); apiRequest.setPath("/rest/160601/ocr/ocr_idcard.json"); apiRequest.setMethod(HttpMethod.POST); // 按照文档设置二进制形式Body,支持设置Query参数、Header参数、Form形式Body apiRequest.setStringBody("{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":\""+imgBase64+"\"},\"configure\":{\"dataType\":50,\"dataValue\":\"{\\\"side\\\":\\\"face\\\"}\"}}]}"); // 设置支持自签等形式的证书,如果服务端证书合法请勿设置该值,仅在开发测试或者非常规场景下设置。 apiRequest.setTrustServerCertificate(true); // 设置超时 apiRequest.setTimeout(10000); rpcService.call(apiRequest, new ApiResponseCallback() { @Override public void onSuccess(ApiResponse apiResponse) { // 处理apiResponse LoadingUtil.dismiss(); String s = apiResponse.getStringBody(); NumBean result = JSONObject.parseObject(s, NumBean.class); String dataValue = result.getOutputs().get(0).getOutputValue().getDataValue(); DataValueBean dataValueBean = JSONObject.parseObject(dataValue, DataValueBean.class); Number = dataValueBean.getNum(); name = dataValueBean.getName(); address = dataValueBean.getAddress(); birth = dataValueBean.getBirth(); nationality = dataValueBean.getNationality(); sex = dataValueBean.getSex(); if(dataValueBean.getError_msg()==null){ runOnUiThread(new Runnable() { public void run() { if(Number == null||Number.equals("")||name == null||name.equals("")||address == null||address.equals("")||birth == null||birth.equals("")||sex == null||sex.equals("")){ Toast.makeText(CardActivity.this, "扫描失败,请重试", Toast.LENGTH_LONG).show(); }else { //扫描成功 } } }); }else { errString = dataValueBean.getError_msg(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(CardActivity.this, "扫描失败,请重试", Toast.LENGTH_LONG).show(); } }); } } @Override public void onException(ApiInvokeException e) { // 处理异常 LoadingUtil.dismiss(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(CardActivity.this, "扫描失败,请重试", Toast.LENGTH_LONG).show(); } }); } }); } }
附:
public class NumBean implements Serializable{ private Listoutputs; public List getOutputs() { return outputs; } public void setOutputs(List outputs) { this.outputs = outputs; } public static class OutputsBean { private String outputLabel; private OutputMultiBean outputMulti; private OutputValueBean outputValue; public String getOutputLabel() { return outputLabel; } public void setOutputLabel(String outputLabel) { this.outputLabel = outputLabel; } public OutputMultiBean getOutputMulti() { return outputMulti; } public void setOutputMulti(OutputMultiBean outputMulti) { this.outputMulti = outputMulti; } public OutputValueBean getOutputValue() { return outputValue; } public void setOutputValue(OutputValueBean outputValue) { this.outputValue = outputValue; } public static class OutputMultiBean { } public static class OutputValueBean { private int dataType; private String dataValue; public int getDataType() { return dataType; } public void setDataType(int dataType) { this.dataType = dataType; } public String getDataValue() { return dataValue; } public void setDataValue(String dataValue) { this.dataValue = dataValue; } } } }
public class DataValueBean implements Serializable{
private String address;
private String birth;
private String config_str;
private String error_msg;
private String name;
private String nationality;
private String num;
private String request_id;
private String sex;
private boolean success;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getConfig_str() {
return config_str;
}
public void setConfig_str(String config_str) {
this.config_str = config_str;
}
public String getError_msg() {
return error_msg;
}
public void setError_msg(String error_msg) {
this.error_msg = error_msg;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getRequest_id() {
return request_id;
}
public void setRequest_id(String request_id) {
this.request_id = request_id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}
在AndroidManifest.xml下添加 Appkey