.NET HttpWebRequest应用

提供基于HttpWebRequest的请求的应用类,其中包含:get请求(带参或不带参)、post请求(json形式)、post请求(xml形式)、文件传输请求

方法的具体说明:

PostHttp2:post请求(json形式)

PostHttp:post请求(xml形式)

GetHttp:get请求(带参或不带参)

PostFile:文件传输请求

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);
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/senyier/p/11125665.html