我正在尝试使用来自Web API的JsonObject
来发布HttpClient
。我不太确定如何解决这个问题,并且在示例代码方面找不到多少内容。
这是我到目前为止所拥有的:
var myObject = (dynamic)new JsonObject();
myObject.Data = "some data";
myObject.Data2 = "some more data";
HttpClient httpClient = new HttpClient("myurl");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.Post("", ???);
我想我需要把我的JsonObject
作为一个StreamContent
,但我已经挂了这一步。
使用新版本的HttpClient并且没有WebApi包它将是:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;
或者如果你想要它是异步的:
var result = await client.PostAsync(url, content);
最简单的方法是使用StringContent
,使用JSON对象的JSON表示。
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
根据您的.NET版本,您还可以使用HttpClientExtensions.PostAsJsonAsync
方法。
https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions.postasjsonasync.aspx
如果使用Newtonsoft.Json:
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
public static class Extensions
{
public static StringContent AsJson(this object o)
=> new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
例:
var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
我没有足够的声誉来为pomber的答案添加评论,所以我发布了另一个答案。使用pomber的方法,我一直收到来自我将JSON请求发布到(Visual Studio 2017,.NET 4.6.2)的API的“400 Bad Request”响应。最终问题被追溯到StringContent()生成的“Content-Type”标头不正确(请参阅https://github.com/dotnet/corefx/issues/7864)。
tl;博士
使用pomber的答案和额外的行来正确设置请求上的标题:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;
vbnet中的代码:
dim FeToSend as new (object--> define class)
Dim client As New HttpClient
Dim content = New StringContent(FeToSend.ToString(), Encoding.UTF8,"application/json")
content.Headers.ContentType = New MediaTypeHeaderValue( "application/json" )
Dim risp = client.PostAsync(Chiamata, content).Result
msgbox(risp.tostring)
希望这有帮助