Web API后端调用接口 (Get,POST,Put,Delete)

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Edc.Dao
{
    public class HttpAPI
    {
        private const string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
        public string Compleatehtml = "";
        private void BugFix_CookieDomain(CookieContainer cookieContainer)
        {
            System.Type _ContainerType = typeof(CookieContainer);
            Hashtable table = (Hashtable)_ContainerType.InvokeMember("m_domainTable",
                                       System.Reflection.BindingFlags.NonPublic |
                                       System.Reflection.BindingFlags.GetField |
                                       System.Reflection.BindingFlags.Instance,
                                       null,
                                       cookieContainer,
                                       new object[] { });
            ArrayList keys = new ArrayList(table.Keys);
            foreach (string keyObj in keys)
            {
                string key = (keyObj as string);
                if (key[0] == '.')
                {
                    string newKey = key.Remove(0, 1);
                    table[newKey] = table[keyObj];
                }
            }
        }

        public String DoGet(String url)
        {
            String html = "";
            StreamReader reader = null;
            HttpWebRequest webReqst = (HttpWebRequest)WebRequest.Create(url);
            webReqst.Method = "GET";
            webReqst.UserAgent = DefaultUserAgent;
            webReqst.KeepAlive = true;
            webReqst.CookieContainer = new CookieContainer();
            webReqst.Timeout = 30000;
            webReqst.ReadWriteTimeout = 30000;
            try
            {
                HttpWebResponse webResponse = (HttpWebResponse)webReqst.GetResponse();
                BugFix_CookieDomain(webReqst.CookieContainer);
                if (webResponse.StatusCode == HttpStatusCode.OK)//&& webResponse.ContentLength < 1024 * 1024
                {
                    Stream stream = webResponse.GetResponseStream();
                    stream.ReadTimeout = 30000;
                    if (webResponse.ContentEncoding == "gzip")
                    {
                        reader = new StreamReader(new GZipStream(stream, CompressionMode.Decompress), Encoding.Default);
                    }
                    else
                    {
                        reader = new StreamReader(stream, Encoding.UTF8);
                    }
                    html = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return html;
        }

        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受    
        }

        public void DoPost(String url, String Content)
        {
            HttpWebRequest webReqst = null;
            //如果是发送HTTPS请求    
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                webReqst = WebRequest.Create(url) as HttpWebRequest;
                webReqst.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                webReqst = WebRequest.Create(url) as HttpWebRequest;
            }
            webReqst.Method = "POST";
            webReqst.UserAgent = DefaultUserAgent;
            webReqst.ContentType = "application/x-www-form-urlencoded";
            webReqst.ContentLength = Content.Length;
            webReqst.CookieContainer = new CookieContainer();
            webReqst.Timeout = 30000;
            webReqst.ReadWriteTimeout = 30000;
            try
            {
                //System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
                byte[] data = Encoding.UTF8.GetBytes(Content);
                webReqst.ContentLength = data.Length;
                Stream stream = webReqst.GetRequestStream();
                stream.Write(data, 0, data.Length);

                webReqst.BeginGetRequestStream(new AsyncCallback(Compleate), webReqst);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void Compleate(IAsyncResult asyncResult)
        {
            //Console.WriteLine("异步完成");
            if (asyncResult == null)
            {
                return;
            }
            HttpWebRequest req = (asyncResult.AsyncState as HttpWebRequest);
            HttpWebResponse res = req.GetResponse() as HttpWebResponse;
            StreamReader reader = new StreamReader(res.GetResponseStream());
            var html = reader.ReadToEnd();
            //Console.WriteLine(reader.ReadToEnd());
            Compleatehtml = html;
        }

        public static string str;
        public static HttpWebRequest request;
        public string DoDelete(String url)
        {
            string urlPath = url;
            //urlPath = urlPath + id;
            int millisecond = 30000;
            WebResponse response = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(urlPath);
                //request.Proxy = null;//关闭代理(重要)
                request.Timeout = millisecond;
                request.Method = "DELETE";
                //request.Accept = "application/json";
                //request.ContentType = "application/json";
                request.ServicePoint.Expect100Continue = false;
                response = (WebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream());
                str = reader.ReadToEnd();
            }
            catch (Exception ex)
            {

                str = "";
            }
            return str;
        }
        public void DoPut(String url, String Content)
        {

            HttpWebRequest webReqst = null;
            //如果是发送HTTPS请求    
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                webReqst = WebRequest.Create(url) as HttpWebRequest;
                webReqst.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                webReqst = WebRequest.Create(url) as HttpWebRequest;
            }
            webReqst.Method = "PUT";
            webReqst.UserAgent = DefaultUserAgent;
            webReqst.ContentType = "application/x-www-form-urlencoded";
            webReqst.ContentLength = Content.Length;
            webReqst.CookieContainer = new CookieContainer();
            webReqst.Timeout = 30000;
            webReqst.ReadWriteTimeout = 30000;
            try
            {
                //System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");
                byte[] data = Encoding.UTF8.GetBytes(Content);
                webReqst.ContentLength = data.Length;
                Stream stream = webReqst.GetRequestStream();
                stream.Write(data, 0, data.Length);

                webReqst.BeginGetRequestStream(new AsyncCallback(Compleate), webReqst);
            }
            catch
            {

            }
        }

    }
}

  

posted @ 2016-06-15 22:09  丶一二丶  阅读(1546)  评论(0编辑  收藏  举报