码迷,mamicode.com
首页 > Web开发 > 详细

HttpHelper之我见

时间:2017-07-03 12:21:56      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:request   ict   settings   请求   post   amp   .net   display   nal   

       前几月一直用一个Http的访问类去调用WebApi,说句实话最开始没觉有什么,一是技术老,二是觉得比较简单,但是最近我一直关注云开发和AI这块儿微软技术,看到云平台调用API大多类似,所以回想这个早年的调用方式,感觉有老汤炖肉之感,实用又有价值,可以作为认识调用API的学习和使用,回味无穷。

    

技术分享
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace Bussiness.Helper
{
    public class HttpHelper
    {
        /// <summary>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        public static HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                
            }
            request.Method = "GET";
            request.Headers.Add("Origin", "http://" + request.Host);

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout;
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                //request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        i++;
                    }
                }
                //byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// 获取请求的数据
        /// </summary>
        public static string GetResponseString(HttpWebResponse webresponse)
        {
            var result = string.Empty;
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                result = reader.ReadToEnd();
            }
            return result;
        }

        /// <summary>
        /// 验证证书
        /// </summary>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors == SslPolicyErrors.None)
                return true;
            return false;
        }
    }
}
View Code

 

特备提示:

乱码现象,注意改这里:

//byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());

调用方式:

技术分享
Dictionary<String, String> pList = new Dictionary<String, String>();
pList.Add("Location", userLog.Location);
pList.Add("Name", userLog.Name);

ResultModel resultModel = new ResultModel();
var apiDomain = ConfigurationManager.AppSettings["ApiDomain"];
var url = @"" + apiDomain + "/api/AD/DeleteOneUser";
// var url = @"" + apiDomain + "/api/AD/GetEmail";
try
{
var response = HttpHelper.CreatePostHttpResponse(url, pList, 0, string.Empty, null);
var info = HttpHelper.GetResponseString(response).Replace("\\", "");
//info = info.Substring(1, info.Length - 2);
//string intoStr = "{" + info + "}";

resultModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ResultModel>(info);

}

catch(){}
View Code

 

HttpHelper之我见

标签:request   ict   settings   请求   post   amp   .net   display   nal   

原文地址:http://www.cnblogs.com/shiningleo007/p/7109755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!