如何使用c#发布JSON到服务器?

下面是我使用的代码:

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";




// turn our request string into a byte stream
byte[] postBytes = Encoding.UTF8.GetBytes(json);


// this is important - make sure you specify type this way
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
request.ContentLength = postBytes.Length;
request.CookieContainer = Cookies;
request.UserAgent = currentUserAgent;
Stream requestStream = request.GetRequestStream();


// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();


// grab te response and print it out to the console along with the status code
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
{
result = rdr.ReadToEnd();
}


return result;

当我运行这个时,我总是得到500个内部服务器错误。

我做错了什么?

845637 次浏览

我的方法是:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";


using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"test\"," +
"\"password\":\"bla\"}";


streamWriter.Write(json);
}


var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

我写了一个库来以更简单的方式执行这个任务,它在这里:https://github.com/ademargomes/JsonRequest

admar的解决方案可以通过利用JavaScriptSerializerSerialize方法来提供对象到JSON的隐式转换来改进。

此外,还可以利用using语句的默认功能来省略显式调用FlushClose

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";


using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
user = "Foo",
password = "Baz"
});


streamWriter.Write(json);
}


var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

如果需要异步调用,则使用

var request = HttpWebRequest.Create("http://www.maplegraphservices.com/tokkri/webservices/updateProfile.php?oldEmailID=" + App.currentUser.email) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/json";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);


private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation


Stream postStream = request.EndGetRequestStream(asynchronousResult);




// Create the post data
string postData = JsonConvert.SerializeObject(edit).ToString();


byte[] byteArray = Encoding.UTF8.GetBytes(postData);




postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();


//Start the web request
request.BeginGetResponse(new AsyncCallback(GetResponceStreamCallback), request);
}


void GetResponceStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
stat.Text = result;
}


}

在Sean的文章中,没有必要嵌套using语句。通过using, StreamWriter将被刷新并在块的末尾关闭,因此不需要显式调用Flush()Close()方法:

var request = (HttpWebRequest)WebRequest.Create("http://url");
request.ContentType = "application/json";
request.Method = "POST";


using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
user = "Foo",
password = "Baz"
});


streamWriter.Write(json);
}


var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

注意你正在使用的内容类型:

application/json

来源:

RFC4627

其他帖子 .

到.Net 4.5.1 这个选项可以工作:

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


var foo = new User
{
user = "Foo",
password = "Baz"
}


await client.PostAsJsonAsync("users/add", foo);
}

我最近提出了一个更简单的方法来发布JSON,额外的步骤是从我的应用程序中的模型转换。注意,你必须为你的控制器创建[JsonObject]模型来获取值并进行转换。

要求:

 var model = new MyModel();


using (var client = new HttpClient())
{
var uri = new Uri("XXXXXXXXX");
var json = new JavaScriptSerializer().Serialize(model);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync(uri,stringContent).Result;
// ...
}

模型:

[JsonObject]
[Serializable]
public class MyModel
{
public Decimal Value { get; set; }
public string Project { get; set; }
public string FilePath { get; set; }
public string FileName { get; set; }
}

服务器端:

[HttpPut]
public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model)
{
// ...
}

var data = Encoding.ASCII.GetBytes(json);

byte[] postBytes = Encoding.UTF8.GetBytes(json);

使用ASCII代替UFT8

一些不同的干净的方法是通过使用HttpClient来实现这一点:

public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
using (var client = new HttpClient())
{
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsJsonAsync(url, resultObject);
}
catch (Exception ex)
{
throw ex
}
return response;
}
}

我最终在同步模式中调用了.Result

HttpResponseMessage response = null;
try
{
using (var client = new HttpClient())
{
response = client.PostAsync(
"http://localhost:8000/....",
new StringContent(myJson,Encoding.UTF8,"application/json")).Result;
if (response.IsSuccessStatusCode)
{
MessageBox.Show("OK");
}
else
{
MessageBox.Show("NOK");
}
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR");
}

HttpClient类型是一个比WebClientHttpWebRequest更新的实现。WebClientWebRequest都被标记为过时。[1]

您可以简单地使用以下几行代码。

string myJson = "{'Username': 'myusername','Password':'pass'}";
using (var client = new HttpClient())
{
var response = await client.PostAsync(
"http://yourUrl",
new StringContent(myJson, Encoding.UTF8, "application/json"));
}

当你不止一次需要你的HttpClient时,建议只创建一个实例并重用它或使用新的HttpClientFactory[2]

对于FTP,由于HttpClient不支持,我们建议使用第三方库。

@learn.microsoft.com [3]


从dotnet core 3.1开始,你可以使用System.Text.Json中的JsonSerializer来创建json字符串。

string myJson = JsonSerializer.Serialize(credentialsObj);

警告!我对这个问题有强烈的看法。

.NET现有的web客户端对开发人员不友好! WebRequest &WebClient是“如何挫败开发者”的主要例子。他们太啰嗦了。复杂的:与之共事的复杂的;当你想在c#中做一个简单的Post请求时。HttpClient在某种程度上解决了这些问题,但它仍然不足。最重要的是,微软的文档很糟糕……真的很糟糕;除非你想翻看一页又一页的技术简介。

有三个优秀的开源,免费的NuGet库作为替代。谢天谢地!这些都得到了很好的支持,有文档记录,是的,很容易纠正……超级容易使用。

  • ServiceStack。文本 -快速,轻和弹性。
  • 简单的REST和HTTP API客户端
  • Flurl-一个流畅,可移植,可测试的HTTP客户端库

它们之间没有太大的差别,但我认为ServiceStack是最好的选择。短信的轻微边缘…

  • Github的星星是大致相同的。
  • 未决问题&重要的是问题解决的速度有多快? ServiceStack获得了最快问题解决的奖项。没有悬而未决的问题。
  • 文档吗?都有很好的文档;然而,ServiceStack把它带到了下一个层次&以其文档的“黄金标准”而闻名。

那么JSON中的Post Request在ServiceStack.Text中是什么样子的呢?

var response = "http://example.org/login"
.PostJsonToUrl(new Login { Username="admin", Password="mypassword" });

这是一行代码。简洁的,简单!将上面的库与. net的Http库进行比较。

我发现这是最友好和最简洁的方式来发布读取JSON数据:

var url = @"http://www.myapi.com/";
var request = new Request { Greeting = "Hello world!" };
var json = JsonSerializer.Serialize<Request>(request);
using (WebClient client = new WebClient())
{
var jsonResponse = client.UploadString(url, json);
var response = JsonSerializer.Deserialize<Response>(jsonResponse);
}

我正在使用Microsoft的System.Text.Json来序列化和反序列化JSON。看到NuGet

我就是这么做的

//URL
var url = "http://www.myapi.com/";


//Request
using var request = new HttpRequestMessage(HttpMethod.Post, url);


//Headers
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Cache-Control", "no-cache");


//Payload
var payload = JsonConvert.SerializeObject(
new
{
Text = "Hello world"
});
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");


//Send
var response = await _httpClient.SendAsync(request);


//Handle response
if (response.IsSuccessStatusCode)
return;

网点网芯方案

首先使用Newtonsoft.Json,然后写一个像这样的方法:

    public static string? LoginToken()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";


using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//  write your json content here
string json = JsonConvert.SerializeObject(new
{
userName = ApiOptions.Username,
password = ApiOptions.Password
}
);




streamWriter.Write(json);
}


var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}


}

这个方法返回string。如果你想将string结果反序列化为JSON,只需在方法的末尾添加这一行:

var result = streamReader.ReadToEnd();
var json_result = JsonConvert.DeserializeObject<LoginTokenResponse>(result); // + add this code
        

哪个LoginTokenResponse是你想反序列化字符串结果的自定义类