如何使用 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; cht=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 内部服务器错误。

我做错了什么?

474

我这样做的方式和工作是:

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

167

Ademar 的解决方案可以通过利用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();
}
110

Http类型是比WebHttpWebRequest更新的实现。WebWebRequest都已标记为过时。[1]

您可以简单地使用以下行。

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

当您多次需要Http时,建议您只创建一个实例并重用它或使用新的HttpFactory[2]

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

@ learn.microsoft.com[3]

由于 dotnet 核心 3.1 你可以使用JsonSerializerSystem.Text.Json来创建你的 JSON 字符串。

string myJson = JsonSerializer.Serialize(credentialsObj);
37

通过usingStreamWriter,它将被刷新并在块的末尾关闭,因此无需显式调用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();
}

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(106)
复制树结构 包括叶子中的单个文件(nicky folder)
上一篇
如何使用CSS在HTML中定位元素
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(49条)