AI开发平台MODELARTS-通过APP认证的方式访问在线服务:方式二:使用Java语言通过AppKey+AppSecret认证鉴权方式发送预测请求

时间:2024-12-10 11:36:21

方式二:使用Java语言通过AppKey+AppSecret认证鉴权方式发送预测请求

  1. 下载Java SDK并在开发工具中完成SDK配置。具体操作请参见在Java环境中集成API请求签名的SDK
  2. 创建Java类,进行预测请求。

    由于在APIG的Java SDK中,“request.setBody()”只支持String类型,所以只支持输入为文本格式的预测请求。

    此处以json格式为例介绍读取本地预测文件并进行base64编码的请求体:

    // Package name of the demo.
    package com.apig.sdk.demo;
    
    import com.cloud.apigateway.sdk.utils.Client;
    import com.cloud.apigateway.sdk.utils.Request;
    import org.apache.http.HttpHeaders;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpRequestBase;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    public class MyAkSkTest {
    
        public static void main(String[] args) {
           # API接口公网地址,例如"https://8e******5fe.apig.******.huaweicloudapis.com/v1/infers/f2682******f42"
            String url = "在线服务的调用地址";
           // 认证用的appKey和appSecret硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;
           // 本示例以appKey和appSecret保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_APP_KEY和HUAWEICLOUD_APP_SECRET。 
            String appKey = System.getenv("HUAWEICLOUD_APP_KEY");
           String appSecret = System.getenv("HUAWEICLOUD_APP_SECRET");
            String body = "{}";
    
            try {
                // Create request
                Request request = new Request();
    
                // Set the AK/AppSecret to sign and authenticate the request.
                request.setKey(appKey);
                request.setSecret(appSecret);
    
                // Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
                request.setMethod(HttpPost.METHOD_NAME);
    
                // Add header parameters
                request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    
                // Set a request URL in the format of https://{Endpoint}/{URI}.
                request.setUrl(url);
    
                // Special characters, such as the double quotation mark ("), contained in the body must be escaped.
                request.setBody(body);
    
                // Sign the request.
                HttpRequestBase signedRequest = Client.sign(request);
    
                // Send request.
                CloseableHttpResponse response = HttpClients.createDefault().execute(signedRequest);
    
                // Print result
                System.out.println(response.getStatusLine().getStatusCode());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    “body”由具体文本格式决定,此处以json为例。

support.huaweicloud.com/usermanual-standard-modelarts/inference-modelarts-0025.html