需要将带有数据的CURL命令转换为VB.net

798qvoo8  于 2022-11-13  发布在  .NET
关注(0)|答案(2)|浏览(187)

我需要转换www.example.com中的cURL字符串VB.net但我不能。我想我创建了一个错误的数据字符串。
这是cURL工作字符串:

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}'

......这是我的代码:

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

回应给予我这个错误:
远程服务器返回错误:(400)错误的请求。
有人能帮帮我吗?

i7uaboj4

i7uaboj41#

这是在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();
cygmwpex

cygmwpex2#

**您的VB.NET代码中的JSON无效。**JSON需要双引号("),但您的VB.NET代码使用的是单引号(')。

在VB.NET字符串文字中,双引号可以通过将其加倍来转义,例如:

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

(最好使用JSON库来创建JSON。)
另外,您的curl代码提供recipient作为JSON数组("recipient": ["1234567890"]),而您的VB.NET代码提供它作为JSON字符串('recipient': '1234567890')。这些小差异相关的:人类读者可以从上下文中推断出你的意图,而Web服务却不能。

相关问题