调用接口有如下两种认证方式,您可以选择其中一种进行认证鉴权。
Token认证:通过Token认证通用请求。
AK/SK认证:通过AK(Access Key ID)/SK(Secret Access Key)加密调用请求。
1.先获取认证接口的认证鉴权(Token认证方式)
public String getToken() throws IOException {
String tokenStr = "";
String value = cacheManager.getValue(Constants.CacheModule.WULIU, "x-subject-token");
if (value!=null){
return value;
}
String iam = "https://iam."+endpoint+"/v3/auth/tokens";
String param = "{\"auth\":{\"identity\":{\"methods\":[\"password\"],\"password\":{\"user\":{\"name\":\"" + username + "\",\"password\":\"" + password + "\",\"domain\":{\"name\":\"" + domainName + "\"}}}},\"scope\":{\"project\":{\"name\":\"cn-north-4\"}}}}";
OutputStreamWriter out;
BufferedReader in = null;
String response = "";
try {
URL url = new URL(iam);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Content-type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
out.write(param);
out.flush();
tokenStr = connection.getHeaderField("x-subject-token");
if (tokenStr.isEmpty()){
return null;
}
cacheManager.setValue(com.ias.assembly.redis.common.Constants.CacheModule.WULIU, "x-subject-token",token,12*60*60);
Map<String, List<String>> map = connection.getHeaderFields();
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
}catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}finally{
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return tokenStr;
}
2.请求认证接口
public JSONObject transportationLicense(String picUrl,String token) throws IOException{
String ocr = "https://ocr."+endpoint+"/v2/"+projectId+"ocr/transportation-license";
System.out.println("华为云OCR请求地址:"+ocr);
String response = "";
BufferedReader in = null;
String param = "{\"url\":\"" + picUrl + "\"}";
try {
URL url = new URL(ocr);
URLConnection connection = url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Auth-Token", token);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
out.write(param);
out.flush();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
response += line;
}
} catch (Exception e) {
System.out.println("POST发送请求出现异常!" + e);
e.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
log.info("图片解析结果:"+response);
JSONObject jsonObject = JSONObject.parseObject(response)
log.info("图片解析结果:"+jsonObject)
return jsonObject;
}