Indonesia
Asked — Edited
Resolved Resolved by DJ Sures!

How To Send JSON &Amp; Set Header Request On Net.Httppost() Method?

Hi everyone, I'm using Net.hTTPPost(url, postData) method on ARC script (JavaScript). I've just realized that this method only send the body payload request as x-www-form-urlencoded. My problems are:

  1. How to send JSON data? I've tried JSON.stringify() but it didn't work as my expectation.
  2. How to set its header request? Here I attach my basic code to make a simple POST request to JSON Placeholder Fake API. I'm curious how to send JSON & how to set its header request.
var resPost = Net.hTTPPost(
   "https://jsonplaceholder.typicode.com/posts";,
   'name=Andy&age=20'
)
print(resPost)

resPost = JSON.parse(resPost)
print(resPost.name)
print(resPost.age)

Run this code & you will see the following log in console:

> {
  "name": "Andy",
  "age": "20",
  "id": 101
}
> Andy
> 20

Hope someone in this community can help me solve this problem. Thanks in advance.


Related Hardware EZ-B IoTiny
Related Controls Script EZ-Script Console

ARC Pro

Upgrade to ARC Pro

Your robot can be more than a simple automated machine with the power of ARC Pro!

#2   — Edited

Thanks for your help, DJ Sures. But if I do like your code:

var body = JSON.stringify({name: 'Andy', age: 28});
var resPost2 = Net.hTTPPost("https://jsonplaceholder.typicode.com/posts";, body)
print(resPost2)

The response will be like this:

{
  "{\"name\":\"Andy\",\"age\":28}": "",
  "id": 101
}

My expectation is like this:

{
  "name": "Andy",
  "age": "28",
  "id": 101
}

By the way, how about my 2nd question? Can you tell me how to set header request? Thanks in advance.

PRO
Synthiam
#3  

The response is because that’s the response from the server that you’re talking to. The response is unaltered. If it’s not formatted as you expect, that’s a conversation you’ll want to have with the server owner.

as for a header request. Are you referring to a url request with embedded parameters?

#4   — Edited

Thanks DJ Sures, you're right. It's the response from the server. I'll try another way.

HTTP headers let the client and the server pass additional information with an HTTP request or response. For example if you make a GET request to https://httpbin.org/get you'll get this response:

{
  "args": {}, 
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", 
    "Accept-Encoding": "gzip, deflate, br", 
    "Accept-Language": "en-US,en;q=0.9", 
    "Host": "httpbin.org", 
    "Sec-Ch-Ua": "\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"92\"", 
    "Sec-Ch-Ua-Mobile": "?0", 
    "Sec-Fetch-Dest": "document", 
    "Sec-Fetch-Mode": "navigate", 
    "Sec-Fetch-Site": "none", 
    "Sec-Fetch-User": "?1", 
    "Upgrade-Insecure-Requests": "1", 
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36", 
    "X-Amzn-Trace-Id": "Root=1-612da020-6cc0ac876e54765643a40a84"
  }, 
  "origin": "114.4.78.239", 
  "url": "https://httpbin.org/get";
}

The headers are Accept, Accept-Encoding, Host, etc. How to set it on ARC? Thanks in advance

PRO
Synthiam
#5   — Edited

There's a few ways you can access the .Net framework CLR from the ARC JavaScript engine. While you could use the System.Net namespace and access the methods yourself, it might make more sense to create a custom JavaScript extension with your needs. It's really easy to do, specifically since you have experience. Plus it's re-usable to it assists others.

The example for it is here: https://synthiam.com/Support/Create-Robot-Skill/Examples/custom-javascript-extension

Essentially, your robot skill subscribes to the ARC JavaScript OnSetValues event and registers your extension method. It's super simple. Just press the CREATE button to create a template to work from.

User-inserted image

The CREATE template will also add a bunch of stuff that you won't need. Such as a ConfigForm and a Configuration class. You can remove those. See the downloadable example in the link above. I posted the Example Project for creating an extension to the JavaScript engine.

That way, you can create a custom ARC JavaScript method for something like...


var resp = Lintangwisesa.requestHTTPHeader("https://myserver.com";, "some header", "header value");

Or even better is to allow the method to accept a key/value pair list of header name and header values. Something like that...:)

PRO
Synthiam
#7  

Ah, because i'm crazy, I wrote it for you. So


    /// /// Post data to a web url as content type application/x-www-form-urlencoded
    /// 
    public string PostWebResponse(string url, string postData, int timeout, string [] headerNames, string [] headerValues) {

      try {

        if (headerNames.Length != headerValues.Length)
          throw new Exception("The count of header names and header values must match. If there are 3 headerNames, there must be 3 headerValues");

        var wr = ARC.WebServiceWrappers.WebRequest.Create(url);
        wr.Method = "POST";
        wr.Timeout = timeout;

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        wr.ContentType = "application/x-www-form-urlencoded";

        for (int i = 0; i < headerNames.Length; i++)
          wr.Headers.Add(
            headerNames[i],
            headerValues[i]);

        wr.ContentLength = byteArray.Length;

        using (Stream dataStream = wr.GetRequestStream())
          dataStream.Write(byteArray, 0, byteArray.Length);

        using (WebResponse response = wr.GetResponse())
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
          return sr.ReadToEnd();
      } catch (WebException webExcp) {

        if (webExcp.Response == null)
          throw;

        using (StreamReader sr = new StreamReader(webExcp.Response.GetResponseStream()))
          return sr.ReadToEnd();
      }

#8   — Edited

Big thanks, Sir! You're awesome! Using this code, you also solved my 1st question. Now I can set the body request content type to application/JSON. Once again thanks for your help. See you on my next questions, Sir;) hehe.

PRO
Synthiam
#9  

Great! there’s so much power by creating custom robot skills. And the ARC framework exposes methods that make it so easy:)