Jason string for post request, error {"Illegal characters in path."}

Obaid 96 Reputation points
2021-08-21T02:05:44.007+00:00

I am using ASP.NET 4.5/VB.NET to POST a API response.
I get {"Illegal characters in path."} error in line 14.
.
My Json string after serialization is :

"{" & vbCrLf & "  ""title"": ""testdata""," & vbCrLf & "  ""body"": ""testbody""," & vbCrLf & "  ""userid"": ""5""," & vbCrLf & "  ""id"": ""50""" & vbCrLf & "}"

The above have some escape characters which I am not sure are the cause because.
I tried hard coding the above string to something like this (tried all single and all double quotes too):

Dim postData As String = "{\'title\':\'testdata\', \'body\':\'testbody\',\'userid\':\'testid\'}"

but this gives same error.

Public Sub ApiCall3()
    Dim WebRequest As WebRequest =
    WebRequest.Create("https://jsonplaceholder.typicode.com/posts")
    WebRequest.Method = "POST"
    WebRequest.ContentType = "application/json"

    Dim dictData As New Dictionary(Of String, Object)
    dictData.Add("title", "testdata")
    dictData.Add("body", "testbody")
    dictData.Add("userid", "5")
    dictData.Add("id", "50")
    Dim postData = JsonConvert.SerializeObject(dictData, Formatting.Indented)

    Dim AWriter As StreamWriter = New StreamWriter(postData)  
    AWriter.Write(postData)
    AWriter.Flush()
    AWriter.Close()

    Dim response As WebResponse = WebRequest.GetResponse()
    Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
    Dim dataStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd
    Console.WriteLine(responseFromServer)
    reader.Close()
    response.Close()
End Sub

If someone could point me i the right direction I would be very grateful.

Windows development Windows API - Win32
0 comments No comments
{count} votes

Accepted answer
  1. Obaid 96 Reputation points
    2021-08-23T15:27:37.247+00:00

    Solved! This woks (for me):

    Public Sub ApiCall103()
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    
            Dim Data2 = "{ ""api_token"":""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"",""customerID"":""8""}"
            Dim httpRequest As WebRequest = WebRequest.Create("https://cleancloudapp.com/api/getCustomer")
            httpRequest.Method = "POST"
    
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(Data2)
            httpRequest.ContentType = "application/jason"
            httpRequest.ContentLength = byteArray.Length
    
            Dim dataStream As Stream = httpRequest.GetRequestStream()
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()
    
            Dim httpResponse As WebResponse = httpRequest.GetResponse()
            Console.WriteLine(CType(httpResponse, HttpWebResponse).StatusDescription)
            dataStream = httpResponse.GetResponseStream()
    
            Dim reader As New StreamReader(dataStream)
            Dim responseFromServer As String = reader.ReadToEnd()
            If responseFromServer = "0" Then
                MsgBox("Login Failed")
            Else
                MsgBox(responseFromServer.ToString)
            End If
            reader.Close()
            dataStream.Close()
            httpResponse.Close()
        End Sub
    

    What I did:

    1. This declaration is important, does not work otherwise: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
    2. Removed Ctype from WebRequest and HttpRequest
    3. Removed "Using" as it caused var not to be Public.
    4. Converted post data, Data2, into byte array.
      Thank you Viorel for your feed back and hope this helps someone!
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-08-21T07:23:58.177+00:00

    Try modifying the problematic line:

    Dim AWriter As StreamWriter = New StreamWriter(WebRequest.GetRequestStream)

    0 comments No comments

  2. Obaid 96 Reputation points
    2021-08-21T14:35:10.7+00:00

    Thank you very much for your reply. Seems that may be the issue.
    I found a solution using WebClient for above and it works, returns json string:

    Public Sub ApiCall5()
            Dim URL As String = "https://jsonplaceholder.typicode.com/posts"
            Dim client As WebClient = New WebClient()
            Dim data As Stream = client.OpenRead(URL)
            Dim reader As StreamReader = New StreamReader(data)
            Dim str As String = ""
            str = reader.ReadLine()
            Do While Not IsNothing(str)
                MsgBox(str)
                str = reader.ReadLine()
            Loop
        End Sub
    

    I converted the above code for the actual url I want to use it for which requires token authentication, please see below.
    But am now getting the error in line 6: {"The underlying connection was closed: An unexpected error occurred on a send."}.

    The documentation for the end pint is here: https://cleancloudapp.com/api/getCustomer.
    Obviously I am doing something wrong. My guess is I am not sending "api_token" correctly.
    In code below I have replaced the secret api token with x's.

    Public Sub ApiCall51()
            Dim URL As String = "https://cleancloudapp.com/api/getCustomer"
            Dim client As WebClient = New WebClient()
            client.Headers(HttpRequestHeader.ContentType) = "application/json"
            client.Headers.Add("api_token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
            Dim data As Stream = client.OpenRead(URL)
            Dim reader As StreamReader = New StreamReader(data)
            Dim str As String = ""
            str = reader.ReadLine()
            Do While Not IsNothing(str)
                MsgBox(str)
                str = reader.ReadLine()
            Loop
        End Sub
    
    0 comments No comments

  3. Obaid 96 Reputation points
    2021-08-21T20:32:34.193+00:00

    I tested the api end point in https://reqbin.com/ and it works.
    But ofcourse it could only export the code in c#:

    var url = "https://cleancloudapp.com/api/getCustomer";
    
    var httpRequest = (HttpWebRequest)WebRequest.Create(url);
    httpRequest.Method = "POST";
    
    httpRequest.ContentType = "application/json";
    
    var data = @"{ ""api_token"":""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"",
            ""customerID"":""8""}";
    
    using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
    {
       streamWriter.Write(data);
    }
    
    var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
       var result = streamReader.ReadToEnd();
    }
    
    Console.WriteLine(httpResponse.StatusCode);
    

    So I managed to translate it to vb.net:

     Public Sub ApiCall10()
            Dim url = "https://cleancloudapp.com/api/getCustomer"
            Dim Data = "{ ""api_token"":""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"",""customerID"":""8""}"
            Dim httpRequest = CType(WebRequest.Create(url), HttpWebRequest)
            httpRequest.Method = "POST"
            httpRequest.ContentType = "application/json"
            Dim StreamWriter = New StreamWriter(httpRequest.GetRequestStream())
            StreamWriter.Write(Data)
            Dim httpResponse = CType(httpRequest.GetResponse(), HttpWebResponse)
            Dim StreamReader = New StreamReader(httpResponse.GetResponseStream())
            Dim result = StreamReader.ReadToEnd()
        End Sub
    

    But unfortunately the same error (line 9):
    {"The underlying connection was closed: An unexpected error occurred on a send."}

    If anyone can help I would be very, very grateful!

    0 comments No comments

  4. Viorel 122.5K Reputation points
    2021-08-21T20:48:17.717+00:00

    The translated code does not include the Using statement. Try this:

    . . .
    Using StreamWriter = New StreamWriter(httpRequest.GetRequestStream())
       StreamWriter.Write(Data)
    End Using
    . . .
    Dim result As String
    Using StreamReader = New StreamReader(httpResponse.GetResponseStream())
       result = StreamReader.ReadToEnd()
    End Using
    . . .
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.