Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am new to development with Web API's. I have figured out how to build and send request to GET data from the the API. I thought I had coded my routines to be able to send a post request, but I have not figured out how to send my JSON string with the data to be posted.

I have included my code and any and all help is greatly appreciated.

Public Async Function MakeRequest(verb As String, resource As String) As Task

        Dim client As HttpClient = New HttpClient
        Dim response As Task(Of HttpResponseMessage)
        Dim result As HttpResponseMessage = New HttpResponseMessage
        Dim request As HttpRequestMessage = New HttpRequestMessage()
        Dim requestp As HttpWebRequest

    Dim queryString As String = Nothing
    ' determine sandbox or live there
    RequestGood = False

    If My.Application.CommandLineArgs(0).ToString() = "S" Then
        uri = New Uri(sandboxuri)
    Else
        uri = New Uri(liveuri)
    End If
         commapikey = "21DDA0A8-9F6B-498A-BD1E-0116C308A263"

        sSignature = GetAuthHeader(softwarekey, apiclientid)

        client = CreateClient(uri, commapikey, apiversion, sSignature)

        headers = GetHeaders(commapikey, apiversion, sSignature)

    Select Case verb
        Case "GET"
            request = BuildRequest(client, HttpMethod.Get, String.Format("{1}?subscription-key={0}", subscriptionkey, resource))
        Case "PUT"
            request = BuildRequest(client, HttpMethod.Put, String.Format("{1}?subscription-key={0}", subscriptionkey, resource))
        Case "POST"
                request = BuildRequest(client, HttpMethod.Post, String.Format("{1}?subscription-key={0}", subscriptionkey, resource))
        Case Else
                request = BuildRequest(client, HttpMethod.Get, String.Format("{1}?subscription-key={0}", subscriptionkey, resource))
        End Select

 
        response = client.SendAsync(request)
 
        result = response.Result

        If result.StatusCode = HttpStatusCode.BadRequest Then
            ' error
        Else
            json = result.Content.ReadAsStringAsync().Result
            RequestGood = True
        End If


End Function
Public Function GetAuthHeader(ByVal key As String, ByVal message As String) As String

    Dim sToken As String = String.Format("{0}:{1}", message, key)
    Dim sReturn As String = Nothing
    Dim bTokenBytes() = System.Text.ASCIIEncoding.UTF8.GetBytes(sToken)
    sReturn = String.Format("Basic {0}", Convert.ToBase64String(bTokenBytes))
    Return sReturn

End Function
 
Public Function CreateClient(ByVal config As Uri, ByVal commApiKey As String, ByVal APIVer As String, ByVal APISignature As String) As HttpClient

        Dim handler As HttpClientHandler = New HttpClientHandler
        Dim client As New HttpClient(handler)
        client.BaseAddress = config
        client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
        client.DefaultRequestHeaders.Add("community-api-key", commApiKey)
        client.DefaultRequestHeaders.Add("api-version", APIVer)
        client.DefaultRequestHeaders.Add("authorization", APISignature)
        If json <> Nothing Then
            client.DefaultRequestHeaders.Add("data", json)
        End If

    Return client

End Function
    Public Function GetHeaders(ByVal commApiKey As String, ByVal APIVer As String, ByVal APISignature As String) As String

        Dim sb As New StringBuilder()
        sb.Append(String.Format("community-api-key:{0}" & Chr(10), commApiKey))
        sb.Append(String.Format("api-version:{0}" & Chr(10), APIVer))
        sb.Append(String.Format("authorization:{0}" & Chr(10), APISignature))
        Return sb.ToString().ToLower()

    End Function

Public Function BuildRequest(ByVal client As HttpClient, ByVal method As HttpMethod, ByVal uri As String) As HttpRequestMessage


        Dim request As HttpRequestMessage = New HttpRequestMessage()
        request.Headers.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
        request.Method = method
        request.RequestUri = New Uri(client.BaseAddress, uri)

    Return request

    End Function
Posted
Comments
Dave-10169531 10-Nov-15 12:02pm    
I guess I thought I could use HttpRequestMessage(). So I need to create a separate function to build my post request.

1 solution

Literally the first result from a Google search for "HttpWebRequest POST"[^]:

...
5. Set the ContentType property to an appropriate value:
request.ContentType = "..."

6. Get the stream that holds request data by calling the GetRequestStream method[^]:
dataStream = request.GetRequestStream()

7. Write the data to the Stream object returned by this method:
dataStream.Write(byteArray, 0, byteArray.Length)

8. Close the request stream by calling the Stream.Close method:
dataStream.Close()

...
 
Share this answer
 
Comments
Dave-10169531 10-Nov-15 12:06pm    
I found that link yesterday and tried to use it. The API is posting to a SQL database not to a Web page. I think that throws me for a loop.
Richard Deeming 10-Nov-15 12:10pm    
But you're still making an HTTP POST request. It doesn't matter what the server does with the request; the process of making the request is still the same.
Dave-10169531 10-Nov-15 12:12pm    
Thank you for your help. I will try it again.
Dave-10169531 10-Nov-15 15:51pm    
Richard thank you for your help. That plus I found an example on the vendors API portal.

I appreciate your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900