C # Post JSON data

Source: Internet
Author: User

public string Post (string Url, String Jsonparas)
{
string strurl = Url;

Create an HTTP request
HttpWebRequest request = (HttpWebRequest) webrequest.create (strURL);
Post request mode
Request. Method = "POST";
Content Type
Request. ContentType = "application/x-www-form-urlencoded";

Setting parameters and URL encoding

String paraurlcoded = Jsonparas;//system.web.httputility.urlencode (Jsonparas);

        byte[] payload;
       //Convert JSON string to bytes  
         Payload = System.Text.Encoding.UTF8.GetBytes (paraurlcoded);
       //Setting the requested contentlength  
         request. ContentLength = payload. Length;
       //Send request, GET request flow  

        Stream Writer;
        try
        {
             writer = Request. GetRequestStream ();//Gets the stream object used to write the request data
       }
         catch (Exception)
        {
             writer = null;
            Console.Write ("Connection server failed!");
       }
       //write request parameters to stream
        writer. Write (payload, 0, payload. Length);
        Writer. Close ();//Closing the request flow

string strvalue = "";//strvalue the character stream returned by the HTTP response
HttpWebResponse response;
Try
{
Get the response stream
Response = (HttpWebResponse) request. GetResponse ();
}
catch (WebException ex)
{
Response = ex. Response as HttpWebResponse;
}

Stream s = response. GetResponseStream ();


Stream postdata = Request.inputstream;
StreamReader sread = new StreamReader (s);
String postcontent = Sread.readtoend ();
Sread.close ();


Return postcontent;//returns JSON data
}


Receive
Get the JSON data structure that came in post
Stream postdata = Request.inputstream;
StreamReader sread = new StreamReader (postdata);
String postcontent = Sread.readtoend ();
Sread.close ();

C # Post JSON data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.