下面是我使用的代码:

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

我做错了什么?


当前回答

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

此外,还可以利用using语句的默认功能,以避免显式调用Flush和Close。

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();
}

其他回答

在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是您要反序列化字符串结果的自定义类

在。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);
}

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

.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,额外的步骤是从我的应用程序中的模型转换。注意,你必须为你的控制器创建模型[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)
{
    // ...
}