0

I'm trying to use vba to post to a web api. The problem is that the parameter is blank in the web api. The web api is written in asp. I called the api from c# and it works but I can't get it to work from vba.

Here is the vba call to the api:

Sub Test()

    Dim http As New MSXML2.XMLHTTP60
   
    http.Open "POST", "http://10.5.72.172:108/api/vbaemail", True

    http.SetRequestHeader "Content-type", "application/json"
    
    Call http.send("abc")
   
End Sub

Here's my simple web api.

public void Post([FromBody] string strJson)
{
    SqlConnection cnnCom = null;
    SqlCommand cmdCom = null;
    string strSql = null;

    //write parameter to table
    cnnCom = new SqlConnection(CF.Get_Connection_String(CF.DatabaseName.COMMON));
    cnnCom.Open();
    strSql =
        "INSERT INTO Test( " +
        "F1) " +
        "VALUES( " +
        "'" + strJson + "')";
    cmdCom = new SqlCommand(strSql, cnnCom);
    cmdCom.ExecuteNonQuery();
    cnnCom.Dispose();
}

Here is the working c# call to the web api:

 static void Main(string[] args)
{
    HttpClient hc = new HttpClient();
    Task<HttpResponseMessage> task1 = null;

    //call web api
    task1 = hc.PostAsJsonAsync<string> 
        ("http://10.5.72.172:108/api/vbaemail", "abc");
}
12

2 Answers 2

0
http.Open "POST", "http://10.5.72.172:108/api/vbaemail", True

instead True set False

Sign up to request clarification or add additional context in comments.

2 Comments

(For the benefit of other readers, True means asynchronous, False means synchronous)
Same thing, the parameter passed to the web api is blank, also I get "operation aborted" during the send command.
0

I was able to get it to work by surrounding the string with single quotes. The problem is I can't use single quotes anywhere in the body being passed to the web api, although there's probably a way to escape them. In our case it's not a big deal, we're just trying to patch some old vba programs that are going away eventually.

Sub Test()

    Dim http As New MSXML2.XMLHTTP60
   
    http.Open "POST", "http://10.5.72.172:108/api/vbaemail", True

    http.SetRequestHeader "Content-type", "application/json"
    
    Call http.send("'" + strJson + "'")  
   
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.