# 通过无认证方式访问在线服务
如果在线服务的状态处于"运行中"，则表示在线服务已部署成功，部署成功的在线服务，将为用户提供一个可调用的API，此API为标准RESTful API。在使用ModelArts部署在线服务时，用户通常希望快速验证模型的效果，ModelArts提供无认证方式访问在线服务，不需要身份验证即可访问在线服务。
通过无认证方式，客户端可以直接调用API，安全性低，适合临时测试的场景/内网调用使用，不建议外网直接使用。建议使用需要验证的认证方式访问服务，比如[通过IAM Token认证的方式访问在线服务](https://support.huaweicloud.com/inference-modelarts/inference2.0-modelarts-0007.html)和[通过API KEY认证访问在线服务](https://support.huaweicloud.com/inference-modelarts/inference2.0-modelarts-0008.html)。
在集成至生产环境之前，需要对此API进行调测，您可以使用以下方式向在线服务发起预测请求：
- [方式一：使用图形界面的软件进行预测（以Postman为例）]
- [方式二：使用curl命令发送预测请求]
- [方式三：使用Python语言发送预测请求]
- [方式四：使用Java语言发送预测请求]
#### 前提条件
- [配置服务信息](https://support.huaweicloud.com/inference-modelarts/inference2.0-modelarts-0016.html#ZH-CN_TOPIC_0000002555517990__section14135916115214)时，认证方式选择"无认证"。
- 调用API时请求并发量、请求体大小以及请求超时时间需小于等于部署时的设定值，否则会导致请求失败。
  图1在线服务无认证配置示例   
  ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002592960588.png)
  
  
 
 #### 获取预测文件的本地路径和在线服务的调用地址
- 预测文件的本地路径：既可使用绝对路径（如Windows格式"D:/test.png"，Linux格式"/opt/data/test.png"），也可以使用相对路径（如"./test.png"）。
- 在线服务的调用地址和输入参数信息：可以在控制台的"模型推理 \> 在线推理"，单击指定在线服务，在"服务"页签的"调用信息"获取。 "调用URL"即在线服务的调用地址。当模型配置文件中apis定义了路径，调用地址后需拼接自定义路径。如："{在线服务的调用地址}/v1/chat/completions"。
  图2获取在线服务API接口地址   
  ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002611744803.png)
  
  
 
 #### 方式一：使用图形界面的软件进行预测（以Postman为例）
1. 下载Postman软件并安装，您也可以直接在Chrome浏览器添加Postman扩展程序（也可使用其他支持发送post请求的软件）。Postman推荐使用8.11.1版本。
2. 打开Postman，如[图3]所示。
   图3Postman界面
   ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002581264936.png)
   
3. 在Postman界面填写参数，以图像分类举例说明。
   - 选择POST任务，将在线服务的调用地址复制到POST后面的方框。
     图4参数填写
     ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002581424846.png)
     
     
   
   - 在Body页签，根据模型的输入参数不同，可分为2种类型：文件输入、文本输入。
     - **文件输入**
       选择"form-data"。在"KEY"值填写模型的入参，和在线服务的输入参数对应，比如本例中预测图片的参数为"images"。然后在"VALUE"值，选择文件，上传一张待预测图片（当前仅支持单张图片预测），如[图5]所示。
       图5填写Body
       ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002611824693.png)
       
       
       
     
     - **文本输入**
       选择"raw"，选择JSON(application/json)类型，在下方文本框中填写请求体，请求体格式与内容与用户部署模型相关，平台不做任何处理。
       图6在线服务无认证方式，文本请求示例   
       ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002581264944.png)
       
       请求体样例如下：
       ```
       {
           "model": "test",
           "messages": [
               {
                   "role": "user",
                   "content": "你是谁？"
               }
           ],
           "max_tokens": 100,
           "top_k": -1,
           "top_p": 1,
           "temperature": 0,
           "ignore_eos": false,
           "stream": false
       }
       ```
       
       
      
    
4. 参数填写完成，单击"send"发送请求，结果会在"Response"下的对话框里显示。
   - 文件输入形式的预测结果样例如[图7]所示，返回结果的字段值根据不同模型可能有所不同。
   
   - 文本输入形式的预测结果样例如[图8]所示，具体返回内容与格式与用户部署模型相关。
     图7文件输入预测结果
     ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002611824683.png)
     
     图8文本输入预测结果
     ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002611744813.png)
     
     
    
 
 #### 方式二：使用curl命令发送预测请求
使用curl命令发送预测请求的命令格式也分为文件输入、文本输入两类。
- 文件输入
  ```
  curl -kv -F 'images=@图片路径' -X POST 在线服务地址
  ```
  - "-k"是指允许不使用证书访问SSL站点。
  
  - "-F"是指上传数据的是文件，本例中参数名为"images"，这个名字可以根据具体情况变化，@后面是图片的存储路径
  
  - "POST"后面跟随的是在线服务的调用地址。
  
  
  curl命令文件输入样例：
  ```
  curl -kv -F 'images=@/home/data/test.png'  -X POST https://{{endpoint}}/v1/infers/eb3e0c54-3dfa-4750-af0c-95c45e5d3e83
  ```
  
- 文本输入
  ```
  curl -kv -d '{"data":{"req_data":[{"sepal_length":3,"sepal_width":1,"petal_length":2.2,"petal_width":4}]}}' -H 'Content-type: application/json' -X POST https://{{endpoint}}/v1/infers/eb3e0c54-3dfa-4750-af0c-95c45e5d3e83
  ```
  "-d"是Body体的文本内容。
  
 #### 方式三：使用Python语言发送预测请求
1. 下载Python SDK并在开发工具中完成SDK配置。具体操作请参见[在Python环境中集成API请求签名的SDK](https://support.huaweicloud.com/devg-apisign/api-sign-sdk-python.html)。
2. 创建请求体，进行预测请求。
   - **输入为文件格式**
     ```
     # coding=utf-8
     import requests
     if __name__ == '__main__':
         # Config url, token and file path.
         url = "在线服务的调用地址"
         file_path = "预测文件的本地路径"
         # Send request.
         files = {
             'images': open(file_path, 'rb')
         }
         resp = requests.post(url, files=files)
         # Print result.
         print(resp.status_code)
         print(resp.text)
     ```
     "files"中的参数名由在线服务的输入参数决定，需要和"类型"为"file"的输入参数"名称"保持一致。以[获取预测文件的本地路径和在线服务的调用地址]里获取的文件预测输入参数"images"为例。
     
   
   - **输入为文本格式（json类型）**
     读取本地预测文件并进行base64编码的请求体示例如下：
     ```
     # coding=utf-8
     import base64
     import requests
     if __name__ == '__main__':
         # Config url, token and file path
         url = "在线服务的调用地址"
         file_path = "预测文件的本地路径"
         with open(file_path, "rb") as file:
             base64_data = base64.b64encode(file.read()).decode("utf-8")
         # Set body,then send request
         headers = {
             'Content-Type': 'application/json',
         }
         body = {
             'image': base64_data
         }
         resp = requests.post(url, headers=headers, json=body)
         # Print result
         print(resp.status_code)
         print(resp.text)
     ```
     "body"中的参数名由在线服务的输入参数决定，需要和"类型"为"string"的输入参数"名称"保持一致。以[获取预测文件的本地路径和在线服务的调用地址]里获取的文本预测输入参数"image"为例。"body"中的base64_data值为string类型。
     
    
 
 #### 方式四：使用Java语言发送预测请求
1. 下载Java SDK并在开发工具中完成SDK配置。具体操作请参见[在Java环境中集成API请求签名的SDK](https://support.huaweicloud.com/devg-apisign/api-sign-sdk-java.html)。
2. （可选）当预测请求的输入为文件格式时，Java工程依赖httpmime模块。
   1. 在工程"libs"中增加httpmime-x.x.x.jar。完整的Java依赖库如[图9]所示。
      httpmime-x.x.x.jar建议使用4.5及以上版本，下载地址：<https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime>。
      图9Java依赖库   
      ![](https://support.huaweicloud.com/inference-modelarts/figure/zh-cn_image_0000002581426980.png) 
   
   2. httpmime-x.x.x.jar添加完成后，在Java工程的.classpath文件中，补充httpmime信息，如下所示：
      ```
      <?xml version="1.0" encoding="UTF-8"?>
      <classpath>
      <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
      <classpathentry kind="src" path="src"/>
      <classpathentry kind="lib" path="libs/commons-codec-1.11.jar"/>
      <classpathentry kind="lib" path="libs/commons-logging-1.2.jar"/>
      <classpathentry kind="lib" path="libs/httpclient-4.5.13.jar"/>
      <classpathentry kind="lib" path="libs/httpcore-4.4.13.jar"/>
      <classpathentry kind="lib" path="libs/httpmime-x.x.x.jar"/>
      <classpathentry kind="lib" path="libs/java-sdk-core-3.1.2.jar"/>
      <classpathentry kind="lib" path="libs/okhttp-3.14.9.jar"/>
      <classpathentry kind="lib" path="libs/okio-1.17.2.jar"/>
      <classpathentry kind="output" path="bin"/>
      </classpath>
      ```
      
    
3. 创建Java类，进行预测请求。
   - **输入为文件格式**
     Java的请求体示例如下：
     ```
     // Package name of the demo.
     package com.apig.sdk.demo;
     import org.apache.http.Consts;
     import org.apache.http.HttpEntity;
     import org.apache.http.client.methods.CloseableHttpResponse;
     import org.apache.http.client.methods.HttpPost;
     import org.apache.http.entity.ContentType;
     import org.apache.http.entity.mime.MultipartEntityBuilder;
     import org.apache.http.impl.client.HttpClients;
     import org.apache.http.util.EntityUtils;
     import java.io.File;
     public class MyTokenFile {
         public static void main(String[] args) {
             // Config url, token and filePath
             String url = "在线服务的调用地址";
             String filePath = "预测文件的本地路径";
             try {
                 // Create post
                 HttpPost httpPost = new HttpPost(url);
                 // Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped.
                 File file = new File(filePath);
                 HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("images", file).setContentType(ContentType.MULTIPART_FORM_DATA).setCharset(Consts.UTF_8).build();
                 httpPost.setEntity(entity);
                 // Send post
                 CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
                 // Print result
                 System.out.println(response.getStatusLine().getStatusCode());
                 System.out.println(EntityUtils.toString(response.getEntity()));
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
     }
     ```
     "addBinaryBody"中的参数名由在线服务的输入参数决定，需要和"类型"为"file"的输入参数"名称"保持一致。此处以[获取预测文件的本地路径和在线服务的调用地址]里获取的"images"为例。
     
   
   - **输入为文本格式（json类型）**
     读取本地预测文件并进行base64编码的请求体示例如下：
     ```
     // Package name of the demo.
     package com.apig.sdk.demo;
     import org.apache.http.HttpHeaders;
     import org.apache.http.client.methods.CloseableHttpResponse;
     import org.apache.http.client.methods.HttpPost;
     import org.apache.http.entity.StringEntity;
     import org.apache.http.impl.client.HttpClients;
     import org.apache.http.util.EntityUtils;
     public class MyTokenTest {
         public static void main(String[] args) {
             // Config url, token and body
             String url = "在线服务的调用地址";
             String body = "{}";
             try {
                 // Create post
                 HttpPost httpPost = new HttpPost(url);
                 // Add header parameters
                 httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                
                 // Special characters, such as the double quotation mark ("), contained in the body must be escaped.
                 httpPost.setEntity(new StringEntity(body));
                 // Send post.
                 CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
                 // Print result
                 System.out.println(response.getStatusLine().getStatusCode());
                 System.out.println(EntityUtils.toString(response.getEntity()));
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
     }
     ```
     "body"由具体文本格式决定，此处以json为例。
     
    
 
