Java 请求华为云认证接口API

调用接口有如下两种认证方式,您可以选择其中一种进行认证鉴权。
Token认证:通过Token认证通用请求。
AK/SK认证:通过AK(Access Key ID)/SK(Secret Access Key)加密调用请求。

1.先获取认证接口的认证鉴权(Token认证方式)

//获取请求链接中用户的token信息
    public String getToken() throws IOException {
        String tokenStr = "";
        //先判断redis中是否有
        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 url = new URL(iam);
            //打开和URL之间的连接
            URLConnection connection = url.openConnection();
            //设置通用的请求属性,请求头部分
            //设置Content-type 为 application/x-www-form-urlencoded
            connection.addRequestProperty("Content-type", "application/json");
            // 发送POST请求必须设置如下两行
            connection.setDoInput(true);
            connection.setDoOutput(true);
            // 建立实际的连接
            connection.connect();

            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();

            //获取相应头中的token信息
            tokenStr = connection.getHeaderField("x-subject-token");

            if (tokenStr.isEmpty()){
                return null;
            }
            //将token放在缓存中 避免多次请求
            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();
            //容易载跟头,表明请求体的部分为json形式
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("X-Auth-Token", token);
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            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块来关闭输入流
        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;
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
要使用Java实现华为云的OBS上传,你可以使用OBS Java SDK提供的API。下面是一个简单的示例代码: 首先需要在pom.xml中添加OBS Java SDK的依赖: ```xml <dependency> <groupId>com.obs</groupId> <artifactId>obs-sdk-java</artifactId> <version>3.20.1</version> </dependency> ``` 然后可以使用以下代码实现文件上传: ```java import com.obs.services.ObsClient; import com.obs.services.exception.ObsException; import com.obs.services.model.PutObjectRequest; import com.obs.services.model.PutObjectResult; import java.io.File; public class ObsUploader { public static void main(String[] args) { String endPoint = "obs.cn-north-1.myhwclouds.com"; // OBS服务的EndPoint String ak = "AccessKeyId"; // 访问OBS的Access Key Id String sk = "SecretAccessKey"; // 访问OBS的Secret Access Key String bucketName = "your-bucket-name"; // 存储桶名称 String objectKey = "your-object-key"; // 对象在OBS中的唯一标识符 File file = new File("your-file-path"); // 待上传的文件路径 ObsClient client = new ObsClient(ak, sk, endPoint); // 创建OBS客户端 try { PutObjectRequest request = new PutObjectRequest(bucketName, objectKey, file); // 创建上传请求 PutObjectResult result = client.putObject(request); // 上传文件 System.out.println("Upload success. ETag: " + result.getEtag()); } catch (ObsException e) { System.out.println("Upload failed. Error message: " + e.getErrorMessage()); } finally { client.close(); // 关闭OBS客户端 } } } ``` 在代码中,需要替换为自己的Access Key Id、Secret Access Key、存储桶名称、对象唯一标识符、待上传文件的路径等信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CXY_BOY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值