下面是我使用的代码:

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

我做错了什么?


当前回答

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

其他回答

我就是这么做的

//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;

我的方法是:

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

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

网点网芯方案

首先使用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现有的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库进行比较。