How to post json data using West Wind in VFP

2.8k views Asked by At

There's a document from West Wind says you can post data using application/json format:

https://west-wind.com/webconnection/docs/_2110q21c9.htm

But when using it, actually it'll do a http get instead of post:

DO wwhttp
oHTTP=CREATEOBJECT("wwHttp")
oHTTP.nHTTPPostMode = 8 oHttp.cContentType = "application/json" oHTTP.AddPostKey("name","somename") lcURL = "https://mywebserver.com/" lcXML = oHTTP.HTTPGet(lcURL)

If using nHTTPPostMode = 1 or 2, the http request parameters are not correctly formatted as json. If I change to 4, it's using Get instead of Post again. Is there anyway to get around this?

1

There are 1 answers

0
Rick Strahl On

When you post JSON data you need to post a JSON document not key value pairs as you are doing in your example. Essentially you need to provide the full content - the entire JSON document as a string - that you're sending to the server (just like the example shows).

To post a JSON document looks like this:

DO wwHttp

oHTTP=CREATEOBJECT("wwHttp")
oHttp.cContentType = "application/json"

lcJson = "{ name: 'somename' }"
oHTTP.AddPostKey(lcJson)  && this sets the entire post buffer

lcURL = "https://mywebserver.com/" 
lcJson = oHTTP.HTTPGet(lcURL)

Using name value pairs only works with POST buffers for URLEncoded or Multipart documents - every other type of content is sent as raw data that you have to provide.

in version 6 and later you can also use the following simpler syntax to .Post data:

oHttp.cContentType = "application/json"
lcJson = oHttp.Post(lcUrl, lcJson)

If you want to create JSON documents under program control you can serialize data using the wwJsonSerializer class (also part of Client Tools). It can serialize from objects, arrays/collections and cursors.