//第一步 創建HTTP請求對象 var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiURL); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; //第二步 生產請求報文 var requestObject = new { method="Query" ,senderId=senderId ,serviceId=serviceId ,userCardId=userCardId ,userCertId=userCertId ,userDept=userDept ,userName=userName , param= new { DataObjectCode = "NNNN" ,Condition="SFZH='11223344'" ,RequiredItems="[\"XM\",\"SFZH\"]" ,InfoCodeMode="1" } }; JavaScriptSerializer js = new JavaScriptSerializer(); string jsonData = js.Serialize(requestObject); //params是C#關鍵字,因此最後代替一下解決。 //'\'單引號在json序列化時會被譯爲unicode編碼,最後解碼便可。 textBox1.Text =jsonData= Regex.Unescape(jsonData.Replace("param", "params")); //DataContractJsonSerializer 序列化JSON須要顯式定義類,且須要標記類成員屬性,比較麻煩暫不用了 //DataContractJsonSerializer dj = new DataContractJsonSerializer(requestObject.GetType()); //MemoryStream msObj = new MemoryStream(); //dj.WriteObject(msObj, requestObject); //textBox1.AppendText("\n" + msObj.ToString()); try { //第三步 發送請求 using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(jsonData); streamWriter.Flush(); streamWriter.Close(); } //第四步 獲得返回報文 var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var resualt = streamReader.ReadToEnd(); textBox2.Text = resualt; } } catch (Exception ex) { textBox2.Text = ex.Message; }