0

I want to POST json values via httpClient into an API. Unfortunately I am quite a beginner and can't handle it. GET works perfectly: here the code for GET:

    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader
    ' Wird für https-Requests benötigt
    System.Net.ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)

    request = DirectCast(WebRequest.Create(url), HttpWebRequest)
    response = DirectCast(request.GetResponse(), HttpWebResponse)
    reader = New StreamReader(response.GetResponseStream())
    Dim s As String
    s = reader.ReadToEnd
    Return s

But how do I realize POST? My API-URL looks like this: https://mydomaine.net/api/auth?token=467445892587458542... an i will send an JSON-String {"test":"value1":"test1":"value2"} I've been working on this problem for many hours. Can someone please help ???

2
  • Set the request.ContentType = "application/json", the request.Method = WebRequestMethods.Http.Post and write to the Request Stream (request.GetRequestStream()) the JSON as UTF-8 bytes, probably. Does this API have any documentation related to posting data? -- Why are you casting SecurityProtocolType to the Tls12 Enum value? Are you still using a .Net Framework version prior to 4.5? Time to update. Commented Jan 13, 2021 at 16:49
  • I am extremely grateful for your help. I have a solution that works now. Commented Jan 13, 2021 at 21:06

1 Answer 1

1

and here is the code that works

Public Function PostRequest(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
    Dim response As String
    Dim request As HttpWebRequest
    ServicePointManager.Expect100Continue = True
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

    request = WebRequest.Create(uri)
    request.ContentLength = jsonDataBytes.Length
    request.ContentType = contentType
    request.Method = method

    Using requestStream = request.GetRequestStream
        requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
        requestStream.Close()

        Using responseStream = request.GetResponse.GetResponseStream
            Using reader As New StreamReader(responseStream)
                response = reader.ReadToEnd()
            End Using
        End Using
    End Using

    Return response
End Function
Sign up to request clarification or add additional context in comments.

1 Comment

ServicePointManager.Expect100Continue = false: your code is not handling the 100Continue response from the server. You should also show how you're calling this method.

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.