C#使用Post調用接口並傳遞json參數

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/json";
            //設置參數,並進行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數據
        }
        //調用:   string askurl = testUrl + "?sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs;
        //string relust = Post(askurl, "");
        // 或者  string relust = Post(askurl, sid=" + sid + "&mobi=" + mobi + "&sign=" + sign + "&msg=" + encodeMsgs);

Post請求參數(發送Json參數、發送普通參數)

1.發送Json格式的Post請求

(1)Post調用

string PostUrl="http://IP:端口/AAA/BBB/CCC";
string id="123";
string Name="小黑";  
JObject patientinfo = new JObject();
JArray ids = new JArray();
ids.Add(id);
patientinfo["ids"] = ids;
patientinfo["Name"] = Name;
string sendData = JsonConvert.SerializeObject(patientinfo);
//eg:  發送Url需要的格式:sendData={"ids":[123],"Name":小黑}
string resultData = Post(sendData, PostUrl);

(2)Post方法

#region Post請求
/// <summary>
 /// http Post請求
 /// </summary>
 /// <param name="parameterData">參數</param>
 /// <param name="serviceUrl">訪問地址</param>
 /// <param name="ContentType">默認 application/json , application/x-www-form-urlencoded,multipart/form-data,raw,binary </param>
 /// <param name="Accept">默認application/json</param>
 /// <returns></returns>
 public string Post(string parameterData, string serviceUrl, string ContentType = "application/json", string Accept = "application/json")
 {
    //先根據用戶請求的uri構造請求地址
    //string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
    //創建Web訪問對象
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
    //把用戶傳過來的數據轉成“UTF-8”的字節流
    byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(parameterData);
    myRequest.Method = "POST";
    //myRequest.Accept = "application/json";
    //myRequest.ContentType = "application/json";  // //Content-Type: application/x-www-form-urlencoded 
    myRequest.AutomaticDecompression = DecompressionMethods.GZip;
    myRequest.Accept = Accept;
    //myRequest.ContentType = ContentType;
    myRequest.ContentType = "application/json; charset=UTF-8";
    myRequest.ContentLength = buf.Length;
    myRequest.MaximumAutomaticRedirections = 1;
    myRequest.AllowAutoRedirect = true;
    //myRequest.Headers.Add("content-type", "application/json");
    //myRequest.Headers.Add("accept-encoding", "gzip");
    //myRequest.Headers.Add("accept-charset", "utf-8");
    //發送請求
    Stream stream = myRequest.GetRequestStream();
    stream.Write(buf, 0, buf.Length);
    stream.Close();
    //通過Web訪問對象獲取響應內容
    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
    //通過響應內容流創建StreamReader對象,因為StreamReader更高級更快
    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
    //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有編碼問題就用這個方法
    string returnData = reader.ReadToEnd();//利用StreamReader就可以從響應內容從頭讀到尾
    reader.Close();
    myResponse.Close();
    return returnData;
}
#endregion

2.帶參數的Post請求

(1)Post調用

string PostUrl="http://IP:端口/AAA/BBB/CCC";
Dictionary<string, string> dic=new Dictionary<string, string>();
dic.Add("Id","123");
dic.Add("Name","笑笑");
string resultData = Post(dic, PostUrl);

(2)Post方法

#region post帶參數的請求
  /// <summary>
    /// 指定Post地址使用Get 方式獲取全部字符串
    /// Post是從服務器上傳送數據
    /// </summary>
    /// <param name="url">請求Url地址</param>
    /// <param name="dic">拼接Url的字段</param>
    /// <returns></returns>
    public static string Post(string url, Dictionary<string, string> dic)
    {
        #region 【網上查的】
        //eg:http://IP:端口/AAA/BBB/CCC//發送對應參數
        #region 創建Web訪問對象
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        //req.Method = "POST";
        //req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        req.AutomaticDecompression = DecompressionMethods.GZip;
        req.ContentType = "application/json; charset=UTF-8";
        #endregion
     #region Post添加並拼接參數,形成對應Url地址
     StringBuilder builder = new StringBuilder();
     int i = 0;
     if (dic.Count > 0)
     {
         foreach (var item in dic)
         {
             if (i > 0)
                 builder.Append("&");
             builder.AppendFormat("{0}={1}", item.Key, item.Value);
             i++;
         }
     }
     #endregion
     #region 發送請求
     byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
     req.ContentLength = data.Length;
     using (Stream reqStream = req.GetRequestStream())
     {
         reqStream.Write(data, 0, data.Length);
         reqStream.Close();
     }
     #endregion
     #region 通過Web訪問對象獲取響應內容
     string result = "";
     HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
     Stream stream = resp.GetResponseStream();
     //獲取響應內容
     using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
     {
         result = reader.ReadToEnd();
     }
     return result;
     #endregion
     #endregion
 }
 #endregion

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: