发送 JSON 内容类型的 POST 请求并在 VB.NET 中显示 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51224722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send a POST request of JSON content-type and display JSON response in VB.NET
提问by Anjum
I am trying to send a POST request to shapeshift which has few parameters to be sent as JSON and then wish to display part of the response in VB.NET
我正在尝试向 shapeshift 发送一个 POST 请求,该请求几乎没有要作为 JSON 发送的参数,然后希望在 VB.NET 中显示部分响应
Documentation from shapeshift: https://info.shapeshift.io/api#api-9
来自 shapeshift 的文档:https: //info.shapeshift.io/api#api-9
Below is what I have tried until now:
以下是我迄今为止所尝试的:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As HttpWebRequest
Dim response As HttpWebResponse
Dim reader As StreamReader
Dim rawresponse As String
Try
request = DirectCast(WebRequest.Create("https://shapeshift.io/sendamount"), HttpWebRequest)
request.ContentType = "application/json"
request.Method = "POST"
Dim postdata As String = "{""amount"":}" + TextBox1.Text + "{,""withdrawal"":}" + TextBox2.Text + "{,""pair"":""btc_eth""}" + "{,""returnAddress"":}" + TextBox3.Text
request.ContentLength = postdata.Length
Dim requestWriter As StreamWriter = New StreamWriter(request.GetRequestStream())
requestWriter.Write(postdata)
requestWriter.Close()
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
rawresponse = reader.ReadToEnd()
Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
Dim json As String = rawresponse
Dim jsonObject As Newtonsoft.Json.Linq.JObject = Newtonsoft.Json.Linq.JObject.Parse(json)
Label1.Text = jsonObject("expiration").ToString
End Sub
ERROR I get is: 400 Bad Request
我得到的错误是:400 Bad Request
I think its because I have messed up something in code where JSON POST request is explained. I did a lot of research and tried few things but nothing worked :(
我认为这是因为我在解释 JSON POST 请求的代码中搞砸了一些东西。我做了很多研究并尝试了一些东西,但没有任何效果:(
回答by Ctznkane525
Try this instead:
试试这个:
Dim postdata As String = "{""amount"":" + TextBox1.Text + "},{""withdrawal"":""" + TextBox2.Text + """},{""pair"":""btc_eth""},{""returnAddress"":""" + TextBox3.Text + """}"
Your data was malformed.
您的数据格式错误。
Or here is another version with String.Format:
或者这里是另一个带有 String.Format 的版本:
Dim postdata2 As String = String.Format("{{""amount"":{0}}},{{""withdrawal"":""{1}""}},{{""pair"":""btc_eth""}},{{""returnAddress"":""{2}""}}", TextBox1.Text, TextBox2.Text, TextBox3.Text)
回答by dbl4k
WebRequest is pretty old now. You may want to use the newer System.Net.Http.HttpClient, official docs are here.
WebRequest 现在已经很老了。您可能想使用较新的 System.Net.Http.HttpClient,官方文档在此处。
Also when transforming to Json, I massively recommend using the Newtonsoft.Json nuget package's JConvert / Deserialize features with generic arguments (Of ...) to convert to a predefined object. Saves a lot of manual text parsing on the return.
同样在转换为 Json 时,我强烈建议使用 Newtonsoft.Json nuget 包的 JConvert / Deserialize 功能和通用参数 (Of ...) 来转换为预定义的对象。在返回时节省了大量手动文本解析。
Have mocked up a quick example:
模拟了一个简单的例子:
Private async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim transaction As New MyRequestData With
{
.Amount = Convert.ToDecimal(TextBox1.Text),
.Withdrawal = Convert.ToDecimal(TextBox2.Text),
.ReturnAddress = TextBox3.Text
}
Dim content = newtonsoft.Json.JsonConvert.SerializeObject(transaction)
dim buffer = System.Text.Encoding.UTF8.GetBytes(content)
Dim bytes = new Net.Http.ByteArrayContent(buffer)
bytes.Headers.ContentType = new Net.Http.Headers.MediaTypeHeaderValue("application/json")
Dim responseBody As string = nothing
Using client As New System.Net.Http.HttpClient
Dim response = Await client.PostAsync("https://shapeshift.io/sendamount",bytes)
responsebody = Await response.Content.ReadAsStringAsync()
End Using
Dim data = Newtonsoft.Json.JsonConvert.DeserializeObject(Of MyResponseData)(responsebody)
If data.Expiration Is Nothing
Label1.Text = data.Error
Else
Label1.Text = data.Expiration
End If
End Sub
Public class MyRequestData
Public property Amount As Decimal
Public property Withdrawal As Decimal
Public property Pair As String = "btc_eth"
Public property ReturnAddress As String
End Class
Public class MyResponseData
Public property Expiration As String
Public property [Error] As String
End Class
Hope this helps, good luck!
希望这有帮助,祝你好运!

