.NET HttpWebRequest應用

提供基於HttpWebRequest的請求的應用類,其中包含:get請求(帶參或不帶參)、post請求(json形式)、post請求(xml形式)、文件傳輸請求html

方法的具體說明:json

PostHttp2:post請求(json形式)cookie

PostHttp:post請求(xml形式)app

GetHttp:get請求(帶參或不帶參)post

PostFile:文件傳輸請求ui

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace xxx.Common.ApiRequest
{
    public static class Request
    {
        public static string PostHttp2(string url, string body)
        {
            byte[] bs = Encoding.UTF8.GetBytes(body);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = bs.Length;

            //Console.WriteLine("完成準備工做");
            using (Stream reqStream = myRequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }

            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                var rs = sr.ReadToEnd();
                return rs;
                //Console.WriteLine("反饋結果" + responseString);
            }
            //Console.WriteLine("完成調用接口");
        }


        /// <summary>
        /// post請求
        /// </summary>
        /// <param name="url">請求url(不含參數)</param>
        /// <param name="body">請求body. 若是是soap"text/xml; charset=utf-8"則爲xml字符串;post的cotentType爲"application/x-www-form-urlencoded"則格式爲"roleId=1&uid=2"</param>
        /// <param name="timeout">等待時長(毫秒)</param>
        /// <param name="contentType">Content-type http標頭的值. post默認爲"text/xml;charset=UTF-8"</param>
        /// <returns></returns>
        public static string PostHttp(string url, string body, string contentType = "text/xml;charset=utf-8")
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = contentType;
            httpWebRequest.Method = "POST";
            //httpWebRequest.Timeout = timeout;//設置超時
            if (contentType.Contains("text/xml"))
            {
                httpWebRequest.Headers.Add("SOAPAction", "http://tempuri.org/mediate");
            }

            byte[] btBodys = Encoding.UTF8.GetBytes(body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            HttpWebResponse httpWebResponse;
            try
            {
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpWebResponse = (HttpWebResponse)ex.Response;
            }

            //HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();
            httpWebResponse.Close();

            return responseContent;
        }
        /// <summary>
        /// get請求
        /// </summary>
        /// <param name="url">請求url(不含參數)</param>
        /// <param name="postDataStr">參數部分:roleId=1&uid=2</param>
        /// <param name="timeout">等待時長(毫秒)</param>
        /// <returns></returns>
        public static string GetHttp(string url, string postDataStr, int timeout = 2000)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.Timeout = timeout;//等待

            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;
        }
        /// <summary>
        /// 傳輸文件到指定接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filePath">文件物理路徑</param>
        /// <returns></returns>
        public static string PostFile(string url, string filePath)
        {
            // 初始化HttpWebRequest
            HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            // 封裝Cookie
            Uri uri = new Uri(url);
            Cookie cookie = new Cookie("Name", DateTime.Now.Ticks.ToString());
            CookieContainer cookies = new CookieContainer();
            cookies.Add(uri, cookie);
            httpRequest.CookieContainer = cookies;

            if (!File.Exists(filePath))
            {
                return "文件不存在";
            }
            FileInfo file = new FileInfo(filePath);

            // 生成時間戳
            string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", strBoundary));

            // 填報文類型
            httpRequest.Method = "Post";
            httpRequest.Timeout = 1000 * 120;
            httpRequest.ContentType = "multipart/form-data; boundary=" + strBoundary;

            // 封裝HTTP報文頭的流
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append(Environment.NewLine);
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("file");
            sb.Append("\"; filename=\"");
            sb.Append(file.Name);
            sb.Append("\"");
            sb.Append(Environment.NewLine);
            sb.Append("Content-Type: ");
            sb.Append("multipart/form-data;");
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());

            // 計算報文長度
            long length = postHeaderBytes.Length + file.Length + boundaryBytes.Length;
            httpRequest.ContentLength = length;

            // 將報文頭寫入流
            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
            }

            // 將報文尾部寫入流
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            // 關閉流
            requestStream.Close();

            using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
            {
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                var rs = sr.ReadToEnd();
                return rs;
                //Console.WriteLine("反饋結果" + responseString);
            }
        }
    }
}
相關文章
相關標籤/搜索