How to post JSON to a server using C#?

后端 未结 13 1609
臣服心动
臣服心动 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:04

    Further to Sean's post, it isn't necessary to nest the using statements. By using the StreamWriter it will be flushed and closed at the end of the block so no need to explicitly call the Flush() and Close() methods:

    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();
    }
    
    0 讨论(0)
  • 2020-11-22 06:06

    I finally invoked in sync mode by including the .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");
    }
    
    0 讨论(0)
  • 2020-11-22 06:15

    The way I do it and is working is:

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

    I wrote a library to perform this task in a simpler way, it is here: https://github.com/ademargomes/JsonRequest

    Hope it helps.

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

    Take care of the Content-Type you are using :

    application/json
    

    Sources :

    RFC4627

    Other post

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

    This option is not mentioned:

    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);
    }
    
    0 讨论(0)
  • 2020-11-22 06:23

    If you need to call is asynchronously then use

    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;
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题