下面是我使用的代码:

// 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个内部服务器错误。

我做错了什么?


当前回答

在Sean的文章中,没有必要嵌套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();
}

其他回答

网点网芯方案

首先使用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;
        }

    }

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

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

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

我最终通过包含.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");
}

在Sean的文章中,没有必要嵌套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现有的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库进行比较。