程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C# Http POST get

C# Http POST get

編輯:C#基礎知識

using System.IO;
using System.Net;

/// <summary>
        /// HttpWebRequest發送Post請求
     /// </summary>
     /// <param name="postUrl"></param>
     /// <param name="paramData"></param>
     /// <param name="dataEncode"></param>
     /// <returns></returns>
        public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            byte[] byteArray = dataEncode.GetBytes(paramData);
            //轉化
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = byteArray.Length;
            Stream newStream = webReq.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            //寫入參數
            newStream.Close();
            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
            ret = sr.ReadToEnd();
            sr.Close();
            response.Close();
            newStream.Close();
            return ret; }
       /// <summary>
        /// WebClient發送Get請求,編碼UTF8
       /// </summary>
       /// <param name="Url"></param>
       /// <returns></returns>
        public static string Get(string Url) {
            string result = "";
      
            HttpWebRequest httpReq;
            httpReq = (HttpWebRequest)WebRequest.Create(new Uri(Url));
            WebResponse wr = httpReq.GetResponse();
            Stream responseStream = wr.GetResponseStream();
            StreamReader respStreamReader = new StreamReader(responseStream);
            result = respStreamReader.ReadToEnd();
            responseStream.Dispose(); wr.Dispose();
            return result;
        }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved