C# TCP客户端编程消息格式为JSON

来源:互联网 发布:远程网络教育的毕业证 编辑:程序博客网 时间:2024/06/15 01:45

---------------------------------------------------初始化头内容---------------------------------------------------------------

class CAuthorization
    {
        private String realmField;
        private String profileField;


        /// <remarks/>
        public string Realm
        {
            get
            {
                return this.realmField;
            }
            set
            {
                this.realmField = value;
            }
        }


        /// <remarks/>
        public string Profile
        {
            get
            {
                return this.profileField;
            }
            set
            {
                this.profileField = value;
            }
        }


        public String toString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("WSSE").Append(" ").Append("realm").Append
              ("=").Append("\"").Append(this.realmField).Append
              ("\"").Append(",").Append(
              " ").Append
              ("profile").Append(
              "=").Append
              ("\"").Append
              (this.profileField).Append("\"");
            return sb.ToString();
        }

        /// <summary>
        ///initial Authorization
        /// </summary>
        public void initalAuthorizationValue()
        {
            this.profileField = "UsernameToken";
            this.realmField = "SDP";

        }

    }

 

 

------------------------------------------------------------------------------------设置XML转为JSON格式------------------------------------

 class RestProcessCustomerRequestClient
    {

              public ProcessCustomerRequestbody createProcessCustomerRequestBody()
        {

            ProcessCustomerRequestbody pcr = new ProcessCustomerRequestbody();

                     .....................

                    return pcr;


        }

        /// <summary>
        /// structure message convert to json format character.
        /// use this function,need to add References "Newtonsoft.Json.dll",see /bin/Debug.
        /// </summary>
        /// <returns>string</returns>
        public string getSerializeJson()
        {
            ProcessCustomerRequestbody customer = createProcessCustomerRequestBody();

            string json = JsonConvert.SerializeObject(customer, Formatting.Indented);

            return json;

        }


    }

 

 

--------------------------------------------------------------------------设置触发驱动事件------------------------------------------------

   private void RequestBT_Click(object sender, EventArgs e)
        {
            /**********************construct http extend headers**********************/
            //initial Authorization
            CAuthorization authorization = new CAuthorization();
            authorization.initalAuthorizationValue();
            //initial XRequestHeader
            XRequestHeader xrequestHeader = new XRequestHeader();
            xrequestHeader.initalXRequestHeadervalue();
            //initial XWSSEHeader
            XWSSEHeader xwsseHeader = new XWSSEHeader();
            xwsseHeader.initalXWSSEHeadervalue();
            //clear any response content.
            textBoxResponse.Text="";

            /*****************construct http request other message***************************/
            //structure RestProcessCustomerRequestClient's instance
            RestProcessCustomerRequestClient restpcr = new RestProcessCustomerRequestClient();
            //the request URL and Port which belong to the SDP.
            //10.135.192.54:8443 is SDP's IPAddress and listen port,maybe it is a simulate server which run as tomcat.
            ///1/generic/processcustomer is request to system local path.
            HttpWebRequest r =
                   WebRequest.Create("http://127.0.0.0:8443/abc")
                   as HttpWebRequest;

            //structure the ProcessCustomerRequestRest message and convert to json message,return string.
            string requestPayload = restpcr.getSerializeJson();

            //use http post method to send message
            r.Method = "POST";

            //add http extended header
            r.Headers.Add("Authorization", authorization.toString());
            r.Headers.Add("X-WSSE", xwsseHeader.toString());
            r.Headers.Add("X-RequestHeader", xrequestHeader.toString());

            //use utf-8 encoding to structure message
            UTF8Encoding encoding = new UTF8Encoding();
            r.ContentLength = encoding.GetByteCount(requestPayload);
            r.Credentials = CredentialCache.DefaultCredentials;
            r.Accept = "application/json";
            r.ContentType = "application/json";

            //Write the payload to the request body.
            using (Stream requestStream = r.GetRequestStream())
            {
                requestStream.Write(encoding.GetBytes(requestPayload), 0,
                    encoding.GetByteCount(requestPayload));
            }
            /*****************deal with HttpWebResponse***************************/
            try
            {
                HttpWebResponse response = r.GetResponse() as HttpWebResponse;
                //return HttpWebResponse,need write io flows into textbox.
                using (Stream rspStm = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(rspStm, Encoding.UTF8))
                    {
                        string line = reader.ReadToEnd();
                        //Receive json Response content
                        textBoxResponse.Text = line.ToString();
                        reader.Close();
                        rspStm.Close();

                    }
                }

            }
            catch (System.Net.WebException ex)
            {
                textBoxResponse.Text = textBoxResponse.Text +
                    "Exception message: " + ex.Message;
                textBoxResponse.Text = textBoxResponse.Text +
                    "\r\nResponse Status Code: " + ex.Status;
                textBoxResponse.Text = textBoxResponse.Text + "\r\n\r\n";
                // get error details sent from the server
                StreamReader reader = new StreamReader(ex.Response.GetResponseStream());
                textBoxResponse.Text = textBoxResponse.Text + reader.ReadToEnd();

            }

        }

 

 

 

 

 

0 0
原创粉丝点击