主要内容

本页采用了机器翻译。点击此处可查看英文原文。

在 Java 客户端中使用协议缓冲区同步 RESTful 请求

R2026b

此示例展示如何使用 Java® 客户端 API、MATLAB® Production Server™ 用于 MATLAB 函数执行的 RESTful API 和协议缓冲区 (protobuf) 发出同步 RESTful 请求。该示例提供并解释了一个示例 Java 客户端 SyncExample.java,用于评估部署在服务器上的 MATLAB 函数。

要在向服务器发出请求时使用 protobuf,请在客户端代码中将 HTTP Content-Type 标头设置为 application/x-google-protobuf。Java 客户端库提供帮助类,以根据 proto 格式内部创建 protobuf 消息并返回相应的字节数组。在 HTTP 请求正文中使用此字节数组。Java 客户端库提供了反序列化 protobuf 响应的方法和类。

要使用 Java 客户端库,必须在 mps_client.jar 中包含 CLASSPATH。

下表显示了何处可以找到示例的 mps_client.jar 文件、Javadoc 和示例代码。

mps_client.jar 的位置
  • MPS_INSTALL/client/java

  • MATLABProductionServer_<release>_Clients/java

Javadoc 的位置
  • MPS_INSTALL/client/java/doc

  • MATLABProductionServer_<release>_Clients/java/doc

示例文件的代码位置
  • MPS_INSTALL/client/java/examples

  • MATLABProductionServer_<release>_Clients/java/examples/MagicSquare

该示例使用 java.net 包发出 HTTP 请求来评估在 http://localhost:9910 上运行的 MATLAB Production Server 实例上部署的 MATLAB 函数。

在服务器上部署您的 MATLAB 函数

编写一个使用 magic (MATLAB) 函数创建幻方的 MATLAB 函数 mymagic,然后将其部署在服务器上。

有关如何部署的信息,请参阅针对 MATLAB Production Server 创建可部署存档。

function m = mymagic(in)

  m = magic(in);
end

函数 mymagic 接受单个 int32 输入并以二维 double 数组的形式返回一个幻方。

向服务器发出同步请求

  1. 构建请求 URL。

    在 Java 客户端中,使用POST Synchronous Request向服务器发出初始请求。请求 URL 包括服务器实例的地址、部署的存档的名称和要评估的 MATLAB 函数的名称。

        String mpsBaseUrl = "http://localhost:9910";
        URL url;
        url = new URL(mpsBaseUrl + "/mymagic/mymagic");

  2. 设置请求标头。

    将 HTTP Content-Type 标头设置为 application/x-google-protobuf,因为 API 返回协议缓冲区消息的字节数组。

        final static protected String CONTENT_TYPE = "application/x-google-protobuf";
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", CONTENT_TYPE);
  3. 创建包含协议缓冲区消息的 HTTP 请求正文。

    函数 mymagic 接受单个 int32 输入并以二维 double 数组的形式返回一个幻方。

    使用 newInstance(arg1, arg2, arg3) 类中定义的 MATLABParams 方法来构建消息。由于 mymagic 函数返回单个二维数组,因此将 arg1 设置为 1,将 arg2 设置为 double[][].class。为 arg3 指定一个整数值,它是 mymagic 函数的输入。

        MATLABParams mlMakeBody = MATLABParams.newInstance(1, double[][].class, 2);
  4. 将请求发送到服务器。

    将 MATLABParams mlMakeBody 对象写入 HTTP 请求的输出流。

        OutputStream output = urlConnection.getOutputStream();
        output.write(mlMakeBody.getRequestBody());
        output.flush();
    

接收并解释服务器响应

成功执行 HTTP 请求后,服务器将使用协议缓冲区消息进行响应。使用 MATLABResult 类的方法解析协议缓冲区消息以获取请求的结果。要创建 MATLABResult 对象,请将 MATLABParams mlMakeBody 对象和 HTTP 请求的响应主体传递给 newInstance 方法。

如果部署的 MATLAB 函数执行时发生错误,则对 getResult 方法的调用将抛出包含来自 MATLAB 的错误消息的 MATLABException。

    MATLABResult<double[][]> mlFinalResult1 = 
        MATLABResult.newInstance(mlMakeBody, urlConnection.getInputStream());
    try{
        double[][] magicSq1 = mlFinalResult1.getResult();
        printResult(magicSq1);
    }catch(MATLABException e){
        e.printStackTrace();
    }

编写一个辅助方法 printResult,将从响应主体解析的结果作为输入并打印相应的二维数组。

    private static void printResult(double[][] result) {
        for (double[] row : result) {
            for (double element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }

SyncExample.java Java 客户端的示例代码如下。

代码:

import com.mathworks.mps.client.MATLABException;
import com.mathworks.mps.client.rest.MATLABParams;
import com.mathworks.mps.client.rest.MATLABResult;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class SyncExample{

	final static protected String CONTENT_TYPE = "application/x-google-protobuf";

    public static void main(String[] args){

        try{
	     // URL of the MATLAB Production Server.
	     String mpsBaseUrl = "http://localhost:9910";

            // Use the java.net package's URLConnection as HTTP Client in this example.		
            URL url;
            url = new URL(mpsBaseUrl + "/mymagic/mymagic");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            //Set Content-Type to protobuf.
            urlConnection.setRequestProperty("Content-Type", CONTENT_TYPE);

            // Make the initial POST request body with MATLABParams class.
            MATLABParams mlMakeBody = MATLABParams.newInstance(1, double[][].class, 2);

            // Write the MATLABParams object into the output stream of the HTTP request.
            OutputStream output = urlConnection.getOutputStream();
            output.write(mlMakeBody.getRequestBody());
            output.flush();

            // Parse the response body of the above HTTP request with methods from the MATLABResult class. 
	      // The MATLABParams object created earlier is an input argument to the newInstance method.
            // If there is any error in MATLAB, call to getResult() throws a MATLABException which
            // contains the error message displayed in MATLAB.
            MATLABResult mlFinalResult1 = MATLABResult.newInstance(mlMakeBody, urlConnection.getInputStream());
            try{
                double[][] magicSq1 = (double[][]) mlFinalResult1.getResult();
                printResult(magicSq1);
            }catch(MATLABException e){
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    // Helper method to print out the magic square generated by MATLAB based on the input.
    private static void printResult(double[][] result) {
        for (double[] row : result) {
            for (double element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
}

另请参阅

主题