C#通過WebClient/HttpWebRequest實現http的post/get方法

來源:互聯網
上載者:User

標籤:code   response   tle   amp   實現   ram   res   odi   author   

//body是要傳遞的參數,格式"roleId=1&uid=2"//post的cotentType填寫://"application/x-www-form-urlencoded"//soap填寫:"text/xml; charset=utf-8"    public static string PostHttp(string url, string body, string contentType)    {        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);        httpWebRequest.ContentType = contentType;        httpWebRequest.Method = "POST";        httpWebRequest.Timeout = 20000;        byte[] btBodys = Encoding.UTF8.GetBytes(body);        httpWebRequest.ContentLength = btBodys.Length;        httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();        StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());        string responseContent = streamReader.ReadToEnd();        httpWebResponse.Close();        streamReader.Close();        httpWebRequest.Abort();        httpWebResponse.Close();        return responseContent;    }POST方法(httpWebRequest)
public static string GetHttp(string url, HttpContext httpContext)    {        string queryString = "?";        foreach (string key in httpContext.Request.QueryString.AllKeys)        {            queryString += key + "=" + httpContext.Request.QueryString[key] + "&";        }        queryString = queryString.Substring(0, queryString.Length - 1);        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + queryString);        httpWebRequest.ContentType = "application/json";        httpWebRequest.Method = "GET";        httpWebRequest.Timeout = 20000;        //byte[] btBodys = Encoding.UTF8.GetBytes(body);        //httpWebRequest.ContentLength = btBodys.Length;        //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();        StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());        string responseContent = streamReader.ReadToEnd();        httpWebResponse.Close();        streamReader.Close();        return responseContent;    }Get方法(HttpWebRequest)
/// <summary>        /// 通過 WebRequest/WebResponse 類訪問遠程地址並返回結果,需要Basic認證;        /// 調用端自己處理異常        /// </summary>        /// <param name="uri"></param>        /// <param name="timeout">訪問逾時時間,單位毫秒;如果不設定逾時時間,傳入0</param>        /// <param name="encoding">如果不知道具體的編碼,傳入null</param>        /// <param name="username"></param>        /// <param name="password"></param>        /// <returns></returns>        public static string Request_WebRequest(string uri, int timeout, Encoding encoding, string username, string password)        {            string result = string.Empty;            WebRequest request = WebRequest.Create(new Uri(uri));            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))            {                request.Credentials = GetCredentialCache(uri, username, password);                request.Headers.Add("Authorization", GetAuthorization(username, password));            }            if (timeout > 0)                request.Timeout = timeout;            WebResponse response = request.GetResponse();            Stream stream = response.GetResponseStream();            StreamReader sr = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding);            result = sr.ReadToEnd();            sr.Close();            stream.Close();            return result;        }        #region # 產生 Http Basic 訪問憑證 #        private static CredentialCache GetCredentialCache(string uri, string username, string password)        {            string authorization = string.Format("{0}:{1}", username, password);            CredentialCache credCache = new CredentialCache();            credCache.Add(new Uri(uri), "Basic", new NetworkCredential(username, password));            return credCache;        }        private static string GetAuthorization(string username, string password)        {            string authorization = string.Format("{0}:{1}", username, password);            return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));        }        #endregionbasic驗證的WebRequest/WebResponse

 

C#通過WebClient/HttpWebRequest實現http的post/get方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.