how to send JSON string to WCF using VBA - json

trying to send a POST to WCF services that accepts JSON string based on the website's JS. I had no luck buy just copy and paste the JSON string in an excel cell and use VBA's XMLHTTP60 to post. Always get bad data (status 400).
tried JSON string and JSON in cell doesn't work. I tried different JSON encoding doesn't seem to work either.
anyidea how I would post a JSON String to WCF?
My guess is somehow the VBA string loses its format during the request. Or different character code \ and : was send.
{"country":"{\"name\":\"USA\",\"population\":\"10000\"}\"}
{"country":"{"name":"USA","population":"10000"}"}
my VBA code
Sub test()
Dim XMLRequest As New MSXML2.XMLHTTP60
website = "URL"
postdata = thisworkbook.worksheets("Sheet1").range("A1").value
XMLRequest.Open "POST", "webSite", False
XMLRequest.SetRequestHeader "Content-Type", "application/json; charset=UTF-8"
XMLRequest.send postdata
end sub
However, I can use a browser console to send the AJAX with no problem.
var data=JSON.Stringify('{"country":"{"name":"USA","population":"10000"}"}');
$Ajax({
method: "POST",
URL: URL,
dataType:json,
contentType: "application/json; charset=UTF-8",
data:data,
cache: false
})
or I have no problem sending javascript in VBA via IE object
IE.Document.parentWindow.execScript "ajax call","javascript"
but my ultimate goal is to bypass IE, since it is not stable especially controlling through VBA.

Related

Requesting URL with UTF-8 characters from VBA code

I am requesting results from this API:
http://mlrs.research.um.edu.mt/resources/gabra-api/
Everything works fine except when I introduce Maltese characters (which are UTF-8).
If I manually request the data using the following URLs, the return is correct.
http://mlrs.research.um.edu.mt/resources/gabra-api/lexemes/search?s=għar
...search?s=ċar (can't post more than two links yet.)
When using the following code, the return is blank.
{"results":[],"query":{"page":1,"page_size":20,"result_count":0,"term":"g?ar","search_lemma":true,"search_wordforms":true,"search_gloss":true,"pending":false,"pos":null,"source":null}}
{"results":[],"query":{"page":1,"page_size":20,"result_count":0,"term":"?ar","search_lemma":true,"search_wordforms":true,"search_gloss":true,"pending":false,"pos":null,"source":null}}
Note ? replacing ħ and ċ characters - that's only because I copied these from the immediate window.
This is the code I am using to make the requests:
Public Function GetWebSource(ByRef Url As String) As String
Dim xml As IXMLHTTPRequest
On Error Resume Next
Set xml = CreateObject("Microsoft.XMLHTTP")
With xml
.Open "GET", Url, False
.send
GetWebSource = .responseText
End With
Set xml = Nothing
End Function
Because VBA IDE does not support these characters, tests will need to be done from a form field.
Any help, much appreciated.
Thanks in advance.
Stephen
The URL contains some non ASCII characters, so you'll have to encode them beforehand:
Set xhr = CreateObject("Microsoft.XMLHTTP")
xhr.Open "GET", "http://mlrs.research.um.edu.mt/resources/gabra-api/lexemes/search?s=g%C4%A7ar", False
xhr.Send

Classic ASP fetch parameters from HTTP using JSON

I have website written using classic asp and i need to create a page that will receive a callback from a third party site which will be sending three parameters using JSON. I then need to store these values in a database.
I have no experience of JSON and need a way to capture the parameters in my asp page.
Anyone have any experience with JSON.
Thanks
I've use http://www.aspjson.com/ for using Classic ASP with JSON.
I downloaded the code from the site above, and have it as an include file on my page:
<!--#INCLUDE file="../dist/asp/aspJSON.asp" -->
Then I can parse through the JSON response and assign variables to it.
I've used it mainly for sending emails using the Mandrill Email API.
The API sends the response in JSON format.
Example response:
[
{
"email": "recipient.email#example.com",
"status": "sent",
"reject_reason": "hard-bounce",
"_id": "abc123abc123abc123abc123abc123"
}
]
Send data to Mandrill...
vurl = "https://mandrillapp.com/api/1.0/messages/send.json"
set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlhttp.open "POST", vurl, false
xmlhttp.setRequestHeader "Content-type","application/json"
xmlhttp.setRequestHeader "Accept","application/json"
'send JSON data to the API
xmlhttp.send oJSON.JSONoutput()
Mandrill then sends a JSON response - e.g.
[
{
"email": "recipient.email#example.com",
"status": "sent",
"reject_reason": "hard-bounce",
"_id": "abc123abc123abc123abc123abc123"
}
]
I can then process it using:
'process the response JSON data
vAnswer = xmlhttp.responseText
I have to remove the square brackets from the start and end of the JSON response:
vAnswer = replace(vAnswer,"[","")
vAnswer = replace(vAnswer,"]","")
And then do stuff with the data:
'load the incoming JSON data using aspJSON
Set oJSON = New aspJSON
'Load JSON string
oJSON.loadJSON(vAnswer)
'set variable values from the incoming data
json_email = ap(oJSON.data("email"))
json_status = ap(oJSON.data("status"))
json_reject_reason = ap(oJSON.data("reject_reason"))
json_id = ap(oJSON.data("_id"))
How you would do it would depend on the structure of the JSON data you are working with.

How to make REST call to Content-Type="application/json" via VBA in Excel?

I'm using Google Chrome REST API to get information from my web server.
I use: Content-Type = "application/json"
and a Post command that includes groovy code inside the Payload (the header remains empty):
{
"aaa": "dan",
"bbb": "my_data",
"ccc": "my_type"
}
or sometimes the Post is empty also in the Payload
This works just fine (I'm getting the response in json format)
I want to post this command with VBA from excel so the response would get into a VBA variable, which I can then print into some cell in the worksheet. How do I do it?
Do I need to download some library for that?
I tried (without success):
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "[my_URL]"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/json"
Worksheets("sheet1").Cells(1, 1)=objHTTP
Please advise,
Needed to add:
objHTTP.setTimeouts 30000, 60000, 30000, 120000

Issue call webservice

Hi I am trying to communicate with a webservice in my asp.net page in my code behind (vb.net) when i make the call I get a 401 unauthorised error however when i try the same call though a simple html page it works.
here is my simple html page
<form method="post" action="https://mycallingwebpage.co.uk/login">
<input type="submit">
</form>
this works fine and returns what i would expect.
however in my vb.net code this doesn't work.
Public Function mylogin(ByVal ServiceProfile) As String
Dim xmldoc As New Xml.XmlDocument
Try
myWebClient = New WebClient
myWebClient.Headers.Add("Content-Type", "text/plain")
Dim bytRetData As Byte() = myWebClient.DownloadData("https://mycallingwebpage.co.uk/login" & ServiceProfile)
Catch ex As Exception
End Try
End Function
I have now made some steps forward.
Further to my earlier question above i am still not able to make the call. I have found that if i make a call to the http url it works but calling the the https url it does not - this ajax call below does work for me - so effectively what do i need to do to convert this code below into a webclient call in vb.net? - this needs to work for https
$.ajax({
type: "POST",
contentType: 'application/x-www-form-urlencoded',
dataType: "application/xml",
crossDomain: true,
data: {'login' : encodeURIComponent('user'),'password' : encodeURIComponent('password')} ,
url: "https://myURL.com",
success: doThis,
error: doThat
});
you have to "authorize" yourself before accessing the WS. You are probably missing an Authorization header. Sorry, I'm not much of a VB expert, but it should be something like this:
myWebClient.Headers.Add("Authorization", "Basic " + ADD_UR_SECRET_HERE)
BTW, don't forget to encode your secret token using a Base64 Encoder before adding it to the headers.
Hope it helped.

.NET MVC3 HttpRequestValidation & JSON

I'm new to MVC3 framework (and .NET overall; Java veteran), so bear with me, but here goes:
Input submitted to a Controller as JSON doesn't seem to be subject to the HttpRequestValidation -- Does that sound right?
I realize if you're receiving data input via JSON you're possibly already doing more work with it, but the Controller Action doesn't seem to necessarily know whether it has JSON data at that point; input values are mapped to parameters just as they would be if they were standard POST params.
Example - I'm asynchronously submitting JSON data to my Controller like the following:
var data = { "title": $titleField.val(), "content": $textArea.val(),
"location": $location.val()
};
$.ajax(submitUrl,
{
type: "POST",
contentType: "application/json; charset=utf-8",
complete: function (data) {
//blah blah
},
dataType: 'json',
data: JSON.stringify(data)
});
}
I then receive the input in my Action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult New(string title = "", string content = "", string location = "")
{
//yada yada
}
Doing this, params are mapped and the user can easily send tags, etc. I'm not turning ValidateInput off, and if I submit with a standard POST and remove the Stringify, it throws the error as expected. Any good reason why JSONified data would skip validation?
Edit - More specific question: If JSONified data will pass HttpRequestValidation, how can we protect against the event where someone would intentionally mock a request to send JSON data instead of post params? I haven't found a way to force the Action method to differentiate between params passed as JSON vs. those passed non-encoded.
Got an answer for my question over on asp.net - See 2nd response.
Solution involves replacing the default ModelBinder.
Any good reason why JSONified data would skip validation?
JSON is encoded => so it ensures that what transits over the wire is safe. When you use JSON.stringify all dangerous characters are encoded.