C# simulate HTTP protocol request

1 Introduction

For details of the http protocol, refer to the HTTP protocol .

WEB commonly used Get and Post requests.

Address bar parameters: if the url is www.viwofer.com?id=12&name=viwofer , then id=12&name=viwofer is the address bar parameter. key1=value&key2=value2 .

Json参数:{"key1":"value","key2":"value2"}

2 GET requests

Common Get requests use address bar parameters

  

        ///  <summary> 
        /// Get data
         ///  </summary> 
        ///  <param name="serverUrl"> Service Url </param> 
        ///  <param name="postData"> Pass parameters, The format is "key1=value&key2=value2" </param> 
        ///  <returns></returns> 
        public  static  string HttpGetConnectToServer( string serverUrl, string postData = "" )
        {
            // Create request   
            var request = (HttpWebRequest)WebRequest.Create(serverUrl + " ? " + postData);
            request.Method = " GET " ;
             // Set the data format of the upload service   
            request.ContentType = " application/x-www-form-urlencoded " ;
             // The requested authentication information is the default   
            request.Credentials = CredentialCache.DefaultCredentials;
             / / Request timeout   
            request.Timeout = 60000 ;
             // Set cookie 
            request.CookieContainer = cookie;

            try
            {
                // Read the return message 
                return GetResponseAsString(request);
            }
            catch (Exception ex)
            {
                //var result = new ServerResult();
                return "{\"error\":\"connectToServer\",\"error_description\":\"" + ex.Message + "\"}";
            }
        }

 

3 Post request

Common Post requests use address bar parameters and Json format parameters.

3.1 The parameter is key1=value&key2=value2

  

        ///  <summary> 
        /// Post get data
         ///  </summary> 
        ///  <param name="serverUrl"> Service Url </param> 
        ///  <param name="postData"> Pass parameters, The format is like "key1=value&key2=value2" </param> 
        ///  <returns></returns> 
        public  static  string HttpPostConnectToServer( string serverUrl, string postData)
        {
            var dataArray = Encoding.UTF8.GetBytes(postData);
            //创建请求  
            var request = (HttpWebRequest)HttpWebRequest.Create(serverUrl);
            request.Method = "POST";
            request.ContentLength = dataArray.Length;
             // Set the data format of the upload service   
            request.ContentType = " application/x-www-form-urlencoded " ;
             // The requested authentication information is the default   
            request.Credentials = CredentialCache.DefaultCredentials;
             / / Request timeout   
            request.Timeout = 600000 ;
             // Set cookie 
            request.CookieContainer = cookie;
             // Create input stream   
            Stream dataStream;

            try
            {
                dataStream = request.GetRequestStream();
            }
            catch (Exception)
            {
                return  null ; // Failed to connect to the server   
            }
             // Send request   
            dataStream.Write(dataArray, 0 , dataArray.Length);
            dataStream.Close();
            // read return message  
             // string res; 
            try
            {
                // Read the return message 
                return GetResponseAsString(request);
            }
            catch (Exception ex)
            {
                // Failed to connect to the server 
                return  " {\"error\":\"connectToServer\",\"error_description\":\" " + ex.Message + " \"} " ;
            }
        }

 

 

3.2     参数为{"key1":"value","key2":"value2"}

 

        ///  <summary> 
        /// Post get data
         ///  </summary> 
        ///  <param name="serverUrl"> Service Url </param> 
        ///  <param name="postData"> Pass parameters, The format is "{"key1":"value","key2":"value2"}" </param> 
        ///  <returns></returns> 
        public  static  string HttpPostJsonConnectToServer( string serverUrl, string postData)
        {
            var dataArray = Encoding.UTF8.GetBytes(postData);
            //创建请求  
            var request = (HttpWebRequest)HttpWebRequest.Create(serverUrl);
            request.Method = "POST";
            request.ContentLength = dataArray.Length;
             // Set the data format of the upload service and pass parameters in json format 
            request.ContentType = " application/json " ;
             // The requested authentication information is the default   
            request.Credentials = CredentialCache.DefaultCredentials;
             // Request timeout   
            request.Timeout = 600000 ;
             // Set cookie 
            request.CookieContainer = cookie;
             // Create input stream   
            Stream dataStream;
             try
            {
                dataStream = request.GetRequestStream();
            }
            catch (Exception)
            {
                return  null ; // Failed to connect to the server   
            }
             // Send request   
            dataStream.Write(dataArray, 0 , dataArray.Length);
            dataStream.Close();
            // read the return message   
            try
            {
                // Read the return message 
                return GetResponseAsString(request);
            }
            catch (Exception ex)
            {
                //连接服务器失败
                //var result = new ServerResult();
                return "{\"error\":\"connectToServer\",\"error_description\":\"" + ex.Message + "\"}";
            }
        }

 

4 Related codes

        //============================初始化Cookie================================
        private static CookieContainer cookie = new CookieContainer();

        // ===================================Get return parameters =========== ============================ 
        private  static  string GetResponseAsString(HttpWebRequest request)
        {
            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string res = reader.ReadToEnd();
                reader.Close(); // Close the read stream 
                response.Close(); // Close the response stream 
                return res;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325900348&siteId=291194637