简体   繁体   English

如何使用WebRequest.Create发布对象?

[英]How do you post an object using WebRequest.Create?

I am working with the Balanced Payments API and trying to figure out how to create a customer. 我正在使用Balanced Payments API并试图找出如何创建客户。

https://docs.balancedpayments.com/current/api.html?language=bash#creating-a-customer https://docs.balancedpayments.com/current/api.html?language=bash#creating-a-customer

The address is passed as an object, though I am unfamiliar with how to pass anything other than a string. 地址作为对象传递,但我不熟悉如何传递除字符串以外的任何内容。 Here is the code I have so far which successfully passes a name and email address: 这是我到目前为止成功传递名称和电子邮件地址的代码:

    Dim request As WebRequest = WebRequest.Create("https://api.balancedpayments.com/v1/customers")
    request.Method = "POST"

    ' get this information from settings in your web config.
    Dim userName As String = "API KEY GOES HERE"

    Dim credentials As String = Convert.ToString(userName & Convert.ToString(":"))
    request.Headers("Authorization") = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials))

    Dim postData As String = "name=John Doe&email=jdoe@domain.com"
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
    request.ContentType = "application/x-www-form-urlencoded"
    request.ContentLength = byteArray.Length
    Dim dataStream As Stream = request.GetRequestStream()
    dataStream.Write(byteArray, 0, byteArray.Length)
    dataStream.Close()

    Dim response As WebResponse = request.GetResponse()

    ' create a data stream.
    dataStream = response.GetResponseStream()

    ' create a stream reader.
    Dim reader As New StreamReader(dataStream)

    ' read the content into a string
    Dim serverResponse As String = reader.ReadToEnd()

    ' clean up.
    reader.Close()
    dataStream.Close()
    response.Close()

I peeked at the API doc and from the looks of it, you don't actually pass an object in the request. 我偷看了API文档,从它的外观来看,你实际上并没有在请求中传递一个对象。 You pass a tag/value pair list of strings. 您传递标记/值对字符串列表。

Here is an excerpt from the API documentation showing an example for creating a bank account: 以下是API文档的摘录,其中显示了创建银行帐户的示例:

curl https://api.balancedpayments.com/v1/bank_accounts \
    -u ak-test-oAm876JsVLRmHwrswIGZ1kaelufk8Cmy: \
    -d "routing_number=121000358" \
    -d "type=checking" \
    -d "name=Johann Bernoulli" \
    -d "account_number=9900000001"

In order to understand this example, you'll need the reference from curl, found here . 为了理解这个例子,你需要curl的引用,在这里找到。

-u Passes the user ID "ak-test-oAm876JsVLRmHwrswIGZ1kaelufk8Cmy" with no password. -u传递没有密码的用户ID“ak-test-oAm876JsVLRmHwrswIGZ1kaelufk8Cmy”。

-d Indicates a tag/value pair in the HTTP POST body. -d表示HTTP POST正文中的标记/值对。 As you can see, there are four lines, each representing one attribute of a bank account. 如您所见,有四行,每行代表一个银行帐户的属性。

So unless something is terribly wrong, the following code ought to do it: 因此,除非出现严重错误,否则以下代码应该这样做:

Dim postData As String = "routing_number=121000358&type=checking&name=Johann+Bernoulli&account_number=9900000001"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()

If this isn't working for you please post additional specifics about the problem. 如果这对您不起作用,请发布有关该问题的其他详细信息。

Incidentally, there's a trick to putting together a well-formed tag value pair list. 顺便提一下,有一个技巧可以将格式良好的标签值对列表组合在一起。 If you create a NameValueCollection using the ParseQueryString static method, it is created internally as an HttpValueCollection and can be used to render querystrings. 如果使用ParseQueryString静态方法创建NameValueCollection,则它在内部创建为HttpValueCollection,可用于呈现查询字符串。 Check it out: 看看这个:

Dim myCollection as NameValueCollection = HttpUtility.ParseQueryString(""); //Create empty collection
myCollection["routing_number"] = "121000358";
myCollection["type"] = "checking";
myCollection["name"] = "Johann Bernoulli";
myCollection["account_number"] = "99900000001";
Dim postData as String = myCollection.ToString();  //Magic!!
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

This will be a lot easier than building the strings yourself when your object has a lot of properties and/or contains data that require escaping. 当您的对象具有大量属性和/或包含需要转义的数据时,这将比自己构建字符串容易得多。


Passing an object with JSON 使用JSON传递对象

The API documentation lacks any examples demonstrating the passing of objects. API文档缺少任何演示对象传递的示例。 Seems we're going to have to guess. 似乎我们不得不猜测。 Boo! 嘘!

I poked about on the web and it seems pretty typical and standard for a RESTful service to pass complex data structures using a format known as a json string (JavaScript Object Notation) which looks something like this: 我在网上讨论过,对于RESTful服务而言,使用称为json字符串 (JavaScript Object Notation)的格式传递复杂数据结构似乎是非常典型和标准的,如下所示:

"address" : { "line1" : "This is line 1 of the address","city":"Seattle","state":"WA"} “地址”:{“line1”:“这是地址的第1行”,“城市”:“西雅图”,“州”:“WA”}

Here is a much more elaborate example but I would suggest starting simple just to ensure this is what the API wants. 这是一个更详细的例子,但我建议开始简单,以确保这是API想要的。

Try hardcoding a simple json string following this pattern and pass it to the service just to see if it works. 尝试按照这种模式对一个简单的json字符串进行硬编码,并将其传递给服务,看它是否有效。

If it does the trick, we can look at easier ways to build the json. 如果它成功,我们可以看看构建json的更简单方法。 If you're on .NET 4.5, check here . 如果您使用的是.NET 4.5,请点击此处 Otherwise you have to do just a little bit more work and implement your own function like this one or as explained in this article . 否则你必须做更多的工作并实现你自己的功能, 如本文本文所述

But the first trick is to verify my guess. 但第一个技巧是验证我的猜测。 It's a pretty good guess since the Balanced Payments API uses json in the response messages (as can be clearly seen in the examples). 这是一个非常好的猜测,因为Balanced Payments API在响应消息中使用了json(在示例中可以清楚地看到)。 Try it and out and let me know what you find. 尝试一下,让我知道你发现了什么。


Passing an object using the Balanced Payments API's funny syntax 使用Balanced Payments API的有趣语法传递对象

OK I kept poking around that API document and found a good example of passing an object . 好的,我一直在探索那个API文档,并找到了一个传递对象好例子

curl https://api.balancedpayments.com/v1/marketplaces/TEST-MP5is34cQM5VCKcHcIfXxLGw/credits \
    -u ak-test-oAm876JsVLRmHwrswIGZ1kaelufk8Cmy: \
    -d "amount=10000" \
    -d "bank_account[routing_number]=121000358" \
    -d "bank_account[type]=checking" \
    -d "bank_account[name]=Johann Bernoulli" \
    -d "bank_account[account_number]=9900000001"

I infer from this example that the way to pass an "object" is to provide the object name and include its properties, one by one, in square brackets. 我从这个例子中推断,传递“对象”的方法是提供对象名称,并在方括号中逐个包含其属性。

So in your case it ought to be 所以在你的情况下它应该是

Dim postData as String = "name=John Doe&address[line1]=123 Main St&address[city]=Baltimore&address[state]=MD&address[postal_code]=21224&email=jdoe@domain.com"

etc. 等等

Give that a try. 试一试。 Third time is the charm? 第三次是魅力?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM