Making a POST API Request in MATLAB
A step-by-step guide converting your Java configuration to MATLAB
Key Highlights
- Secure SSL/TLS Setup: Configure MATLAB to use SSL certificates and truststore files similarly to Java.
- XML Request Handling: Read the XML file from disk and use it as the request body for the POST API call.
- HTTP Request Options: Use MATLAB’s HTTP interface with proper parameters and error handling.
Overview
In this guide, we demonstrate the process of converting a Java configuration for making a secure POST API request to an equivalent MATLAB script. In the Java configuration, you have specified various parameters such as the endpoint URL, certificate details, file paths for requests and responses, and the data type (XML). We will use MATLAB’s native HTTP interface – part of the matlab.net.http package – to recreate a similar behaviour.
Step-by-Step Configuration and Code Explanation
1. Define the Endpoint and File Paths
The Java configuration uses the endpoint https://mpc.sem-o.com/mws/. Begin by setting the endpoint and file paths in MATLAB. Create variables for the truststore and certificate files as well as directories for the request and response files. This modular structure ensures that modifying the file paths in the future is straightforward.
Endpoint and File Configuration
Define the endpoint and file paths like so:
% Define endpoint URL
url = 'https://mpc.sem-o.com/mws/';
% Define certificate and truststore paths and credentials
certDir = './certs/';
certFile = 'TOOLKITUSER@PY_034000.p12';
certPassword = '123456';
trustStore = fullfile(certDir, 'server-ca.jks');
trustStorePassword = '123456';
% Define directories for request and response files
inputDir = './request-files/';
outputDir = './response-files/';
inputFile = 'sem_qry_pn_submit.xml';
2. Reading the XML Request File
Since your request data type is XML, you need to read the contents of the XML file before submitting it as a payload. MATLAB’s fileread function is ideal for this purpose.
Load XML Data
Below is the code snippet for loading your XML file:
% Construct full path for the XML file
xmlFilePath = fullfile(inputDir, inputFile);
% Read the XML content into a string variable
xmlContent = fileread(xmlFilePath);
3. Configure MATLAB's HTTP Request Options and SSL/TLS Details
MATLAB provides the matlab.net.http.HTTPOptions class to set options for secure HTTP communication. Although MATLAB does not natively support Java keystores like .jks or .p12 files directly, you must supply these files' paths via the HTTP options. Recent MATLAB releases allow you to provide the CertificateFilename, CertificateFilePassword, and trust store details through similar property names.
Configuring HTTP Options with SSL/TLS
Use the following code snippet to configure the certificate and trust store options:
% Set up HTTP Options including SSL/TLS certificate details
options = matlab.net.http.HTTPOptions(...
'CertificateFilename', fullfile(certDir, certFile), ...
'CertificateFilePassword', certPassword, ...
'TrustStoreName', trustStore, ...
'TrustStorePassword', trustStorePassword, ...
'Timeout', 30); % Set timeout (in seconds)
This code sets the certificate filename and password that match your Java configuration, and similarly establishes the truststore file.
4. Creating the HTTP POST Request
MATLAB’s matlab.net.http.RequestMessage class allows you to construct a HTTP request. You will specify the method as POST and set the Content-Type header to application/xml.
Constructing the Request Message
Follow these steps when building the HTTP request:
import matlab.net.*
import matlab.net.http.*
% Construct the URI
uri = URI(url);
% Create a POST HTTP request message
request = RequestMessage('POST');
% Set request header for XML Content-Type
request.Header = HeaderField('Content-Type', 'application/xml');
% Set the XML content as the body of the request
request.Body = MessageBody(xmlContent);
Here, the URI object encapsulates the API endpoint, and the MessageBody is populated with the XML content. The header is crucial as it tells the server to expect XML data.
5. Sending the Request and Handling the Response
Next, you will send the HTTP request using the send method. Handling the response appropriately allows you to verify whether the request was processed successfully and to read any data sent back by the API.
Submitting the Request and Processing the Response
The following code snippet demonstrates sending the request and capturing the response:
try
% Send the HTTP request
[response, completedRequest] = send(request, uri, options);
% Check if response has the expected status code
if response.StatusCode == matlab.net.http.StatusCode.OK
% Capture response data
responseData = response.Body.Data;
fprintf('Request successful. Received response:\n%s\n', char(responseData));
% Optionally, save the response to an output file
outputFilePath = fullfile(outputDir, 'response.xml');
fid = fopen(outputFilePath, 'w');
if fid ~= -1
fwrite(fid, responseData);
fclose(fid);
disp('Response saved to file.');
else
error('Unable to open response file for writing.');
end
else
disp(['Request failed with status code: ' char(response.StatusCode)]);
end
catch exception
% Error handling – display error message
disp('An error occurred while sending the HTTP request:');
disp(exception.message);
end
This section wraps the request submission in a try-catch block to capture any errors during transmission or processing. Success is checked by verifying that the status code is OK (200). The response is printed to the console and, if needed, written to a specified output XML file.
Comprehensive MATLAB Script
Combining the steps above, below is the full MATLAB script that mirrors your Java configuration:
| MATLAB Script Outline | |
|---|---|
| Section | Description |
| Endpoint and File Paths | Definition of URL for API and file paths for certificates, request XML, and response output. |
| File Reading | Uses fileread to import XML file content for the POST request. |
| HTTP Options | Configures SSL/TLS settings using CertificateFilename and TrustStore properties. |
| Request Message | Creates a POST HTTP request message with appropriate headers and payload. |
| Sending and Handling | Sends the HTTP request, processes the response, and handles potential errors. |
% Define endpoint URL and paths
url = 'https://mpc.sem-o.com/mws/';
certDir = './certs/';
certFile = 'TOOLKITUSER@PY_034000.p12';
certPassword = '123456';
trustStore = fullfile(certDir, 'server-ca.jks');
trustStorePassword = '123456';
inputDir = './request-files/';
outputDir = './response-files/';
inputFile = 'sem_qry_pn_submit.xml';
% Read XML content
xmlFilePath = fullfile(inputDir, inputFile);
xmlContent = fileread(xmlFilePath);
% Configure HTTP options with SSL/TLS information
options = matlab.net.http.HTTPOptions(...
'CertificateFilename', fullfile(certDir, certFile), ...
'CertificateFilePassword', certPassword, ...
'TrustStoreName', trustStore, ...
'TrustStorePassword', trustStorePassword, ...
'Timeout', 30);
% Import necessary packages
import matlab.net.*
import matlab.net.http.*
% Build the URI and request message
uri = URI(url);
request = RequestMessage('POST');
request.Header = HeaderField('Content-Type', 'application/xml');
request.Body = MessageBody(xmlContent);
% Send the request and handle response
try
[response, completedRequest] = send(request, uri, options);
if response.StatusCode == matlab.net.http.StatusCode.OK
responseData = response.Body.Data;
fprintf('Request successful. Received response:\n%s\n', char(responseData));
% Save response to file
outputFilePath = fullfile(outputDir, 'response.xml');
fid = fopen(outputFilePath, 'w');
if fid ~= -1
fwrite(fid, responseData);
fclose(fid);
disp('Response saved to file.');
else
error('Unable to open response file for writing.');
end
else
disp(['Request failed with status code: ' char(response.StatusCode)]);
end
catch exception
disp('An error occurred while sending the HTTP request:');
disp(exception.message);
end
Additional Considerations
Certificate Handling in MATLAB
It is important to note that MATLAB’s handling of certificates may not be as transparent as in Java. Ensure that your MATLAB version supports the configuration options used. If MATLAB does not directly interpret .jks or .p12 files as expected, you may have to convert them to a suitable format or use system-level configurations. Refer to recent MATLAB documentation on SSL/TLS setup, as updates may improve compatibility.
Timeouts and Error Handling
The HTTPOptions object includes a timeout parameter to prevent the request from hanging indefinitely. In robust implementations, further error handling should be added, especially for network issues or certificate errors.
Testing and Verification
After constructing your request, test it in a controlled environment to ensure that certificates are being loaded properly and the endpoint is correctly responding. Using MATLAB’s debugging and logging functions will greatly simplify troubleshooting any issues that arise during the POST request submission.
References
- HTTP Interface - MathWorks
- RequestMessage Class - MathWorks
- Send HTTP Message - MathWorks
- Setting the Body in POST Request - MATLAB Central
- POST Requests with Authorization Tokens - MATLAB Central
Recommended Queries for Further Insights
Last updated March 5, 2025