1. 程式人生 > >C#後臺向某個網站傳送Get或者Post請求

C#後臺向某個網站傳送Get或者Post請求

C#通過後臺進行想某個網站傳送Get或者POST請求。

這個沒有多少內容,就直接上程式碼了,下面的是GET請求:

      public string GetFunction(string order,string payType,string filePrice)
        {
            請求的地址(你請求的地址如果不需要引數就傳參),
           string serviceAddress = "http://域名/pay-0.0.1-SNAPSHOT/pay? 
           jobId="+order+"&payType="+payType+"&price="+filePrice;
            try
            {
                HttpWebRequest request = 
               (HttpWebRequest)WebRequest.Create(serviceAddress);
                request.Method = "GET";//GET請求的方式
                request.ContentType = "text/html;charset=UTF-8";//編碼格式以及請求型別,這行程式碼很關鍵,不設定ContentType將可能導致後臺引數獲取不到值
                request.Credentials = CredentialCache.DefaultCredentials;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, 
                 Encoding.UTF8);
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;//返回連結字串
            }
            catch (Exception e)
            {

                throw new Exception("請求錯誤"+e);
            }
        }


Post請求:

 //Post請求
        public static string Post(string url, string obj = null)
        {
            string param = (obj);//引數
            byte[] bs = Encoding.Default.GetBytes(param);

            //建立一個新的HttpWebRequest物件。
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

            // 將方法屬性設定為“POST”以將資料釋出到URI。
            req.Method = "POST";

            //設定contentType屬性。
            req.ContentType = "application/json";

            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
                HttpWebResponse response2 = (HttpWebResponse)req.GetResponse();
                StreamReader sr2 = new StreamReader(response2.GetResponseStream(), 
               Encoding.UTF8);
                string str = sr2.ReadToEnd();
                return str;
            }

        }