How to post JSON to a server using C#?

后端 未结 13 1589
臣服心动
臣服心动 2020-11-22 05:55

Here\'s the code I\'m using:

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.Protoco         


        
相关标签:
13条回答
  • 2020-11-22 06:23

    var data = Encoding.ASCII.GetBytes(json);

    byte[] postBytes = Encoding.UTF8.GetBytes(json);

    Use ASCII instead of UFT8

    0 讨论(0)
  • 2020-11-22 06:25

    I find this to be the friendliest and most concise way to post an read JSON data:

    var url = @"http://www.myapi.com/";
    var request = new Request { Greeting = "Hello world!" };
    var json = JsonSerializer.Serialize<Request>(request);
    using (WebClient client = new WebClient())
    {
        var jsonResponse = client.UploadString(url, json);
        var response = JsonSerializer.Deserialize<Response>(jsonResponse);
    }
    

    I'm using Microsoft's System.Text.Json for serializing and deserializing JSON. See NuGet.

    0 讨论(0)
  • 2020-11-22 06:27

    The HttpClient type is a newer implementation than the WebClient and HttpWebRequest.

    You can simply use the following lines.

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

    When you need your HttpClient more than once it's recommended to only create one instance and reuse it or use the new HttpClientFactory.

    0 讨论(0)
  • 2020-11-22 06:28

    Ademar's solution can be improved by leveraging JavaScriptSerializer's Serialize method to provide implicit conversion of the object to JSON.

    Additionally, it is possible to leverage the using statement's default functionality in order to omit explicitly calling Flush and 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();
    }
    
    0 讨论(0)
  • 2020-11-22 06:28

    WARNING! I have a very strong view on this subject.

    .NET’s existing web clients are not developer friendly! WebRequest & WebClient are prime examples of "how to frustrate a developer". They are verbose & complicated to work with; when all you want to do is a simple Post request in C#. HttpClient goes some way in addressing these issues, but it still falls short. On top of that Microsoft’s documentation is bad … really bad; unless you want to sift through pages and pages of technical blurb.

    Open-source to the rescue. There are three excellent open-source, free NuGet libraries as alternatives. Thank goodness! These are all well supported, documented and yes, easy - correction…super easy - to work with.

    • ServiceStack.Text - fast, light and resilient.
    • RestSharp - simple REST and HTTP API Client
    • Flurl- a fluent, portable, testable HTTP client library

    There is not much between them, but I would give ServiceStack.Text the slight edge …

    • Github stars are roughly the same.
    • Open Issues & importantly how quickly any issues closed down? ServiceStack takes the award here for the fastest issue resolution & no open issues.
    • Documentation? All have great documentation; however, ServiceStack takes it to the next level & is known for its ‘Golden standard’ for documentation.

    Ok - so what does a Post Request in JSON look like within ServiceStack.Text?

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

    That is one line of code. Concise & easy! Compare the above to .NET’s Http libraries.

    0 讨论(0)
  • 2020-11-22 06:29

    I recently came up with a much simpler way to post a JSON, with the additional step of converting from a model in my app. Note that you have to make the model [JsonObject] for your controller to get the values and do the conversion.

    Request:

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

    Model:

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

    Server side:

    [HttpPut]     
    public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model)
    {
        ...
        ... 
    }
    
    0 讨论(0)
提交回复
热议问题