简体   繁体   English

发送JSON内容类型的POST请求并在VB.NET中显示JSON响应

[英]Send a POST request of JSON content-type and display JSON response in VB.NET

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 我正在尝试将POST请求发送到shapeshift,该请求几乎没有要作为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错误的请求

I think its because I have messed up something in code where JSON POST request is explained. 我认为是因为我弄乱了解释JSON POST请求的代码中的某些内容。 I did a lot of research and tried few things but nothing worked :( 我做了很多研究,尝试了几件事,但没有任何效果:(

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)

WebRequest is pretty old now. WebRequest现在已经很老了。 You may want to use the newer System.Net.Http.HttpClient, official docs are here . 您可能要使用较新的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. 另外,在转换为Json时,我强烈建议使用带有通用参数(Of ...)的Newtonsoft.Json nuget包的JConvert / Deserialize功能转换为预定义的对象。 Saves a lot of manual text parsing on the return. 在返回时节省大量手动文本解析。

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! 希望这有帮助,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 烧瓶中没有POST请求和Content-Type“application / json”的响应 - No response with POST request and Content-Type “application/json” in flask 当'Content-Type'设置为'application / json'时,无法发送帖子请求 - Can't send a post request when the 'Content-Type' is set to 'application/json' AngularJS无法使用Content-Type:application / json发送post请求 - AngularJS can't send post request with Content-Type:application/json Android中用于内容类型的JSON对象的HTTP POST请求问题 - Problems with HTTP POST request for JSON object for content-type in Android Sails js http post 请求,内容类型为:application/json - Sails js http post request with content-type: application/json POST 请求失败(放心测试)预期的响应正文将被验证为 JSON、HTML 或 XML,但没有在响应中定义内容类型。? - POST request fails (rest-assured test) Expected response body to be verified as JSON, HTML or XML but no content-type was defined in the response.? 使用VB.NET在URL HTTP Web请求上发布JSON - Post JSON on URL HTTP Web Request with VB.NET 将JSON对象作为POST请求发送时出错[VB.NET] - Error sending JSON object as a POST request [VB.NET] VB.NET JSON POST 请求中的错误 - HTTPWEBREQUEST - Error in VB.NET JSON POST request - HTTPWEBREQUEST 具有JSON内容类型的PUT请求 - PUT request with json content-type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM