How to set parameters to send a string to a server using a http request?
17 views (last 30 days)
Show older comments
I am trying to send the value of a string variable called seq to a url. I dont get an error message, but I fail t send it properly, always getting a "400/BadRequet" status. I am familiar with MATLAB, but not with http requests, message bodies and headers. A colleague said I needed to send the parameters as key-value pairs which is why I now have 'seq' and '30' under r.Body.ContentType.MediaInfo.Parameters. But it still doesnt work. Anyone have any idea?
seq = "30";
import matlab.net.*
import matlab.net.http.*
body = MessageBody(seq);
r = RequestMessage('post',[],body);
r.Header = matlab.net.http.field.ContentTypeField('plain/text');
newType = setParameter(r.Body.ContentType.MediaInfo,'seq',seq)
r.Header = matlab.net.http.field.ContentTypeField(newType);
uri = URI('http://10.10.XX.XX:8080/measurements-seq');
resp = send(r,uri);
status = resp.StatusCode
0 Comments
Answers (1)
Swastik Sarkar
on 19 Feb 2024
I understand you are experiencing some difficulty with making an HTTP POST request to your server. While I cannot be certain about the specifics of your server application or the exact cause of the 400 Bad Request error without more information, I am happy to offer some guidance that might help you troubleshoot the issue.
Given that you are using a POST request with key-value pairs, I am assuming you are looking to send data in a JSON format. Here is how you can write your MATLAB code to send a simple JSON request body:
seq = "30";
import matlab.net.http.*
import matlab.net.http.field.*
json = jsonencode(struct('seq', seq));
disp(json);
body = MessageBody(json);
contentTypeField = ContentTypeField('application/json');
r = RequestMessage('POST', [contentTypeField], body);
uri = 'http://10.10.XX.XX:8080/measurements-seq';
resp = send(r, uri);
status = resp.StatusCode;
disp(status);
If you are still facing the 400 Bad Request error after using this code, it would be beneficial to examine the response body for more specific details regarding the error. The server may provide additional information in the response body, which can give you clues about what needs to be corrected. You can access the response body using resp.Body.Data.
For a detailed guide on making HTTP requests in MATLAB, please visit this site:
I hope this code adjustment helps you out. If the issue persists, please feel free to share more details about the server's expected request format or any additional error messages you might be receiving, I will be glad to assist.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!