C# Post Json數據


public string Post(string Url, string jsonParas)
    {
        string strURL = Url;

        //創建一個HTTP請求 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
        //Post請求方式 
        request.Method = "POST";
        //內容類型
        request.ContentType = "application/x-www-form-urlencoded";

        //設置參數,並進行URL編碼 

        string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   

        byte[] payload;
        //將Json字符串轉化為字節 
        payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
        //設置請求的ContentLength  
        request.ContentLength = payload.Length;
        //發送請求,獲得請求流 

        Stream writer;
        try
        {
            writer = request.GetRequestStream();//獲取用於寫入請求數據的Stream對象
        }
        catch (Exception)
        {
            writer = null;
            Console.Write("連接服務器失敗!");
        }
        //將請求參數寫入流
        writer.Write(payload, 0, payload.Length);
        writer.Close();//關閉請求流

        String strValue = "";//strValue為http響應所返回的字符流
        HttpWebResponse response;
        try
        {
            //獲得響應流
            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;//返回Json數據
    }


//接收
  //獲取post過來的json數據結構
                    Stream postData = Request.InputStream;
                    StreamReader sRead = new StreamReader(postData);
                    string postContent = sRead.ReadToEnd();
                    sRead.Close();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM