AI开发平台MODELARTS-访问在线服务(AK/SK认证):方式二:使用Java语言发送预测请求

时间:2024-09-05 08:29:58

方式二:使用Java语言发送预测请求

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

    由于在APIG的Java SDK中,“request.setBody()”只支持String类型,所以只支持输入为文本格式的预测请求。如果输入的是文件格式,需要先进行base64编码转换成文本。

    • 输入为文件格式
      此处以json格式为例介绍读取本地预测文件并进行base64编码的请求体,请求体示例如下:
      package com.apig.sdk.demo;
      import com.cloud.apigateway.sdk.utils.Client;
      import com.cloud.apigateway.sdk.utils.Request;
      import org.apache.commons.codec.binary.Base64;
      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;
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.io.InputStream;
      public class MyAkSkTest2 {
          public static void main(String[] args) {
              String url = "在线服务的调用地址";
             // 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;
             // 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。 
              String ak = System.getenv("HUAWEICLOUD_SDK_AK");
             String sk = System.getenv("HUAWEICLOUD_SDK_SK");
              String filePath = "预测文件的本地路径";
              try {
                  // Create request
                  Request request = new Request();
                  // Set the AK/SK to sign and authenticate the request.
                  request.setKey(ak);
                  request.setSecret(sk);
                  // 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);
                  // build your json body
                  String body = "{\"image\":\"" + getBase64FromFile(filePath) + "\"}";
                  // 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();
              }
          }
          /**
           * Convert the file into a byte array and Base64 encode it
           * @return
           */
          private static String getBase64FromFile(String filePath) {
              // Convert the file into a byte array
              InputStream in = null;
              byte[] data = null;
              try {
                  in = new FileInputStream(filePath);
                  data = new byte[in.available()];
                  in.read(data);
                  in.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              // Base64 encode
              return new String(Base64.encodeBase64(data));
          }
      }

      使用base64编码方式,需要在模型推理代码中增加对请求体解码的代码。

    • 输入为文本格式(json类型)
      // 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) {
              String url = "在线服务的调用地址";
             // 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;
             // 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。 
              String ak = System.getenv("HUAWEICLOUD_SDK_AK");
             String sk = System.getenv("HUAWEICLOUD_SDK_SK");
      
              try {
                  // Create request
                  Request request = new Request();
      
                  // Set the AK/SK to sign and authenticate the request.
                  request.setKey(ak);
                  request.setSecret(sk);
      
                  // 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.
                  String body = "{}";
                  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/inference-modelarts/inference-modelarts-0024.html