Home > database >  Need to convert a CURL command with Data to VB.net
Need to convert a CURL command with Data to VB.net

Time:10-20

I need to convert a cURL string in VB.net but I'm not able. I suppose I create a wrong data string.

This is the cURL working string:

curl -XPOST 'https://app.esendex.it/API/v1.0/REST/sms'
-H 'Content-Type: application/json'
-H 'user_key: MyKey' -H 'Session_key: MySessionKey' 
-d '{"message_type": "N", "message": "Hello!", "recipient": ["1234567890"], "sender": "Bill", "returnCredits": true}'

...and this is my code:

   Private Sub SendMessage()
    Dim webRequest As WebRequest = WebRequest.Create("https://app.esendex.it/API/v1.0/REST/sms")
    Dim myReq As HttpWebRequest

    Dim myData As String = "{'message_type': 'N', 'message': 'Hello!', 'recipient': '1234567890', 'sender': 'Bill, 'returnCredits': true}"
    Dim web As New Net.WebClient
    web.Headers.Add(Net.HttpRequestHeader.Accept, "application/json")
    web.Headers.Add(Net.HttpRequestHeader.ContentType, "application/json")
    web.Headers.Add("user_key", Chiavi(0))
    web.Headers.Add("Session_key", Chiavi(1))
    Dim response = web.UploadString("https://app.esendex.it/API/v1.0/REST/sms", "POST", myData)
    Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(response)

    myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)

End Sub

Response give me this error:

The remote server returned an error: (400) Bad Request.

Can someone help me ?

CodePudding user response:

This is how it would be done in C#.

using System.Net.Http.Headers;

HttpClient client = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://app.esendex.it/API/v1.0/REST/sms");

request.Headers.Add("user_key", "MyKey");
request.Headers.Add("Session_key", "MySessionKey");

request.Content = new StringContent("{\"message_type\": \"N\", \"message\": \"Hello!\", \"recipient\": [\"1234567890\"], \"sender\": \"Bill\", \"returnCredits\": true}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();

CodePudding user response:

The JSON in your VB.NET code is invalid. JSON requires double quotes ("), but your VB.NET code uses single quotes (').

Double quotes can be escaped in VB.NET string literals by doubling them, e.g.

Dim myData As String = "{""message_type"": ""N"", ...

(Better yet, use a JSON library to create your JSON.)

Also not that your curl code provides recipient as a JSON array ("recipient": ["1234567890"]), whereas your VB.NET code provides it as a JSON string ('recipient': '1234567890'). These small differences are relevant: A human reader can infer your intent from context, a web service can't.

  • Related