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

Ars*_*ray 246 c# post json httpwebrequest

这是我正在使用的代码:

// 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;
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我总是得到500内部服务器错误.

我究竟做错了什么?

小智 367

我这样做并且正在工作的方式是:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

希望能帮助到你.

  • 我会想到streamWriter.Flush(); 和streamWriter.Close(); 没有必要,因为你在使用块内.在使用块结束时,流编写器仍会关闭. (32认同)
  • 我认为json字符串行应该是:string json ="{\"user \":\"test \","+"\"password \":\"bla \"}"; 看起来你错过了一个\ (3认同)
  • @ user3772108请参阅/sf/answers/1146604511/.使用JSON库(如Newtonsoft JSON.Net),从对象呈现JSON字符串,或使用序列化.我知道这里为了简单起见省略了(尽管简单性增加很少),但是格式化结构化数据字符串(JSON,XML,...)太危险了,即使在琐碎的场景中也是如此,并且鼓励人们复制这样的代码. (3认同)
  • 始终使用"application/json"(除非出于其他原因需要text/json,例如:http://www.entwicklungsgedanken.de/2008/06/06/problems-with-internet-explorer-and-applicationjson/) .Creding转到:http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type. (2认同)

Sea*_*son 140

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 这使用JavaScriptSerializer的Serialize方法来创建有效的JSON而不是手工制作它. (15认同)
  • @LuzanBaral您只需要一个程序集:System.Web.Extensions (2认同)
  • `JavaScriptSerializer` 在 dot net core 中不起作用。另一种方法是“使用 Newtonsoft.Json”并调用:“ string json = JsonConvert.SerializeObject(new {Username="Blahblah"});” (2认同)

NtF*_*reX 42

HttpClient类型是比WebClient和更新的实现HttpWebRequest.

您只需使用以下行.

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"));
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当您需要HttpClient多次时,建议仅创建一个实例并重复使用或使用新实例HttpClientFactory.

  • 关于HttpClient的一点说明,通常的共识是您不应该丢弃它。即使实现了IDisposable对象,该对象也是线程安全的,可以重用。/sf/ask/1099356471/ (3认同)

Dav*_*rke 31

继Sean的帖子之后,没有必要嵌套using语句.通过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();
}
Run Code Online (Sandbox Code Playgroud)


Jea*_* F. 13

照顾您正在使用的内容类型:

application/json
Run Code Online (Sandbox Code Playgroud)

资料来源:

RFC4627

其他帖子


Viv*_*ara 12

如果需要异步调用则使用

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

    }
Run Code Online (Sandbox Code Playgroud)

  • 感谢您发布此解决方案Vivek.在我们的场景中,我们在这篇文章中尝试了另一个解决方案,并且在我们的应用程序中看到了System.Threading异常,因为我假设是同步帖子阻塞线程.您的代码解决了我们的问题 (2认同)

Dus*_*tin 11

我最近提出了一种更简单的发布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;
     ...
     ...
  }
Run Code Online (Sandbox Code Playgroud)

模型:

[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; }
}
Run Code Online (Sandbox Code Playgroud)

服务器端:

[HttpPut]     
public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model)
{
    ...
    ... 
}
Run Code Online (Sandbox Code Playgroud)


Pro*_*ark 8

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

.NET 现有的 Web 客户端对开发人员不友好! WebRequestWebClient是“如何挫败开发人员”的主要示例。它们冗长而复杂;当您只想在 C# 中执行一个简单的 Post 请求时。HttpClient在某种程度上解决了这些问题,但它仍然不足。最重要的是,微软的文档很糟糕……真的很糟糕;除非你想筛选一页又一页的技术简介。

开源来拯救。有三个优秀的开源免费 NuGet 库作为替代。谢天谢地!这些都得到了很好的支持,记录在案,是的,很容易 - 更正......超级容易 - 使用。

  • ServiceStack.Text - 快速、轻便且有弹性。
  • RestSharp - 简单的 REST 和 HTTP API 客户端
  • Flurl - 流畅、便携、可测试的 HTTP 客户端库

它们之间没有太多关系,但我会给 ServiceStack.Text 一点优势……

  • Github star大致相同。
  • 未解决的问题 & 重要的是任何问题的关闭速度有多快?ServiceStack 在这里因最快的问题解决和没有未解决的问题而获奖。
  • 文档?都有很好的文档;然而,ServiceStack 将其提升到了一个新的水平,并以其文档的“黄金标准”而闻名。

好的 - 那么 ServiceStack.Text 中的 JSON 格式的 Post 请求是什么样的?

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

那是一行代码。简洁大方!将上述内容与 .NET 的 Http 库进行比较。


Cen*_*tro 6

未提及此选项:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 自.Net 4.5.2起,此选项不再可用.请参见http://stackoverflow.com/a/40525794/2161568 (2认同)

Dim*_*ron 5

实现此目的的一些不同且干净的方法是使用 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;
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 很有帮助,但是从 .NET 4.5.2 开始,`PostAsJsonAsync` 不再可用。改用`PostAsync`。更多[这里](/sf/answers/2421644361/) (4认同)