c# post basic 接口

          string url = "http://xxxxxxxxx";//地址,请反复检查地址的准确性
                string usernamePassword =  "username:password";

                byte[] bytes = Encoding.Default.GetBytes(usernamePassword);
                string str = Convert.ToBase64String(bytes);

                string ret = new RequestHelper().HttpBasicPost(url, unionid, str);

public class RequestHelper
    {

        /// <summary>
        /// 设置cookie
        /// </summary>
        private CookieContainer cookie;

        public CookieContainer Cookie
        {
            get { return cookie; }
            set { cookie = value; }
        }

        /// <summary>
        /// 是否允许重定向
        /// </summary>
        private bool allowAutoRedirect = true;
        /// <summary>
        /// 是否允许重定向(默认:true)
        /// </summary>
        public bool AllowAutoRedirect
        {
            get { return allowAutoRedirect; }
            set { allowAutoRedirect = value; }
        }

        /// <summary>
        /// contentType
        /// </summary>
        private string contentType = "application/x-www-form-urlencoded";
        /// <summary>
        /// 设置contentType(默认:application/x-www-form-urlencoded)
        /// </summary>
        public string ContentType
        {
            get { return contentType; }
            set { contentType = value; }
        }

        /// <summary>
        /// accept
        /// </summary>
        private string accept = "*/*";
        /// <summary>
        /// 设置accept(默认:*/*)
        /// </summary>
        public string Accept
        {
            get { return accept; }
            set { accept = value; }
        }

        /// <summary>
        /// 过期时间(默认:30000)
        /// </summary>
        private int timeOut = 30000;

        public int TimeOut
        {
            get { return timeOut; }
            set { timeOut = value; }
        }

        private string userAgent;
        /// <summary>
        ///
        /// </summary>
        public string UserAgent
        {
            get { return userAgent; }
            set { userAgent = value; }
        }
        private string acceptLanguage;
        /// <summary>
        /// 接受的语言
        /// </summary>
        public string AcceptLanguage
        {
            get { return acceptLanguage; }
            set { acceptLanguage = value; }
        }
        /// <summary>
        /// 处理POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postdata"></param>
        /// <returns></returns>
        public string HttpPost(string url, string postdata)
        {
            var request = CreateWebRequest(url);
            request.Method = "POST";
            if (!string.IsNullOrWhiteSpace(postdata))
            {
                var bytesToPost = Encoding.UTF8.GetBytes(postdata);
                request.ContentLength = bytesToPost.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytesToPost, 0, bytesToPost.Length);
                    requestStream.Close();
                }
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    var result = sr.ReadToEnd();
                    return result;
                }
            }
        }

        public string HttpBasicPost(string url, string postdata, string basic)
        {
            var request = CreateWebRequest(url);
            request.Method = "POST";
            request.Headers.Add("Authorization", "Basic " + basic);
            if (!string.IsNullOrWhiteSpace(postdata))
            {
                var bytesToPost = Encoding.UTF8.GetBytes(postdata);
                request.ContentLength = bytesToPost.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytesToPost, 0, bytesToPost.Length);
                    requestStream.Close();
                }
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    var result = sr.ReadToEnd();
                    return result;
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public T HttpPost<T>(string url, object obj)
        {
            var resultStr = HttpPost(url, JsonConvert.SerializeObject(obj));
            return JsonConvert.DeserializeObject<T>(resultStr);
        }
        public T HttpPost<T>(string url, object obj, out string result, Func<string, string> serializeStrFunc = null)
        {
            var str = JsonConvert.SerializeObject(obj);
            if (serializeStrFunc != null)
            {
                str = serializeStrFunc(str);
            }
            result = HttpPost(url, str);
            return JsonConvert.DeserializeObject<T>(result);
        }
        /// <summary>
        /// post请求返回html
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public string HttpPost(string url, Dictionary<string, string> postdata)
        {
            string postDataStr = null;
            if (postdata != null && postdata.Count > 0)
            {
                postDataStr = string.Join("&", postdata.Select(it => it.Key + "=" + it.Value));
            }
            return HttpPost(url, postDataStr);
        }
        /// <summary>
        /// get请求获取返回的html
        /// </summary>
        /// <param name="url">无参URL</param>
        /// <param name="querydata">参数</param>
        /// <returns></returns>
        public string HttpGet(string url, Dictionary<string, string> querydata)
        {
            if (querydata != null && querydata.Count > 0)
            {
                url += "?" + string.Join("&", querydata.Select(it => it.Key + "=" + it.Value));
            }
            return HttpGet(url);
        }
        /// <summary>
        /// get请求获取返回的html
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string HttpGet(string url)
        {
            HttpWebRequest request = CreateWebRequest(url);
            request.Method = "GET";
            // response.Cookies = cookie.GetCookies(response.ResponseUri);
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    var result = sr.ReadToEnd();
                    return result;
                }
            }
        }

        protected HttpWebRequest CreateWebRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //request.ContentType = "text/html;charset=UTF-8";
            request.ContentType = this.ContentType;
            if (cookie != null)
                request.CookieContainer = this.Cookie;
            if (string.IsNullOrEmpty(this.AcceptLanguage))
            {
                WebHeaderCollection myWebHeaderCollection = request.Headers;
                myWebHeaderCollection.Add("Accept-Language", this.AcceptLanguage);
            }
            request.Accept = this.Accept;
            request.UseDefaultCredentials = true;
            request.UserAgent = this.UserAgent;
            request.Timeout = this.TimeOut;
            request.AllowAutoRedirect = this.AllowAutoRedirect;
            this.SetCertificatePolicy();
            return request;
        }

        /// <summary>
        /// POST文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file">文件路径</param>
        /// <param name="postdata"></param>
        /// <returns></returns>
        public string HttpUploadFile(string url, string file, Dictionary<string, string> postdata)
        {
            return HttpUploadFile(url, file, postdata, Encoding.UTF8);
        }
        /// <summary>
        /// POST文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="file">文件路径</param>
        /// <param name="postdata">参数</param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public string HttpUploadFile(string url, string file, Dictionary<string, string> postdata, Encoding encoding)
        {
            return HttpUploadFile(url, new string[] { file }, postdata, encoding);
        }
        /// <summary>
        /// POST文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files">文件路径</param>
        /// <param name="postdata">参数</param>
        /// <returns></returns>
        public string HttpUploadFile(string url, string[] files, Dictionary<string, string> postdata)
        {
            return HttpUploadFile(url, files, postdata, Encoding.UTF8);
        }
        /// <summary>
        /// POST文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files">文件路径</param>
        /// <param name="postdata">参数</param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public string HttpUploadFile(string url, string[] files, Dictionary<string, string> postdata, Encoding encoding)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            HttpWebRequest request = CreateWebRequest(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true; ;
            request.AllowAutoRedirect = this.AllowAutoRedirect;
            if (this.Cookie != null)
                request.CookieContainer = this.Cookie;
            request.Credentials = CredentialCache.DefaultCredentials;

            using (Stream stream = request.GetRequestStream())
            {
                //1.1 key/value
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                if (postdata != null)
                {
                    foreach (string key in postdata.Keys)
                    {
                        stream.Write(boundarybytes, 0, boundarybytes.Length);
                        string formitem = string.Format(formdataTemplate, key, postdata[key]);
                        byte[] formitembytes = encoding.GetBytes(formitem);
                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                //1.2 file
                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                for (int i = 0; i < files.Length; i++)
                {
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
                    byte[] headerbytes = encoding.GetBytes(header);
                    stream.Write(headerbytes, 0, headerbytes.Length);
                    using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
                    {
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            stream.Write(buffer, 0, bytesRead);
                        }
                    }
                }

                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                return stream.ReadToEnd();
            }
        }

        /// <summary>
        /// 获得响应中的图像
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public Stream GetResponseImage(string url)
        {
            Stream stream = null;
            try
            {
                HttpWebRequest request = CreateWebRequest(url);
                request.KeepAlive = true;
                request.Method = "GET";
                HttpWebResponse res = (HttpWebResponse)request.GetResponse();
                stream = res.GetResponseStream();
                return stream;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 正则获取匹配的第一个值
        /// </summary>
        /// <param name="html"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        private string GetStringByRegex(string html, string pattern)
        {
            Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matchs = re.Matches(html);
            if (matchs.Count > 0)
            {
                return matchs[0].Groups[1].Value;
            }
            else
                return "";
        }
        /// <summary>
        /// 正则验证返回的response是否正确
        /// </summary>
        /// <param name="html">Html内容</param>
        /// <param name="pattern">正则表达式</param>
        /// <returns></returns>
        private bool VerifyResponseHtml(string html, string pattern)
        {
            Regex re = new Regex(pattern);
            return re.IsMatch(html);
        }
        //注册证书验证回调事件,在请求之前注册
        private void SetCertificatePolicy()
        {
            ServicePointManager.ServerCertificateValidationCallback
                       += RemoteCertificateValidate;
        }
        /// <summary> 
        /// 远程证书验证,固定返回true
        /// </summary> 
        private static bool RemoteCertificateValidate(object sender, X509Certificate cert,
            X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }

        #region 提交方式
        /// <summary>
        /// 提交Https
        /// Post
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="parsStr">参数</param>
        public static string  SubmitHttpsPost(string url, string parsStr)
        {
            Encoding encode = System.Text.Encoding.UTF8;
            byte[] arrB = encode.GetBytes(parsStr);
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = arrB.Length;
            Stream outStream = myReq.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();

            //接收HTTP做出的响应
            WebResponse myResp = myReq.GetResponse();
            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string str = null;
            while (count > 0)
            {
                str += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();

            if (!string.IsNullOrEmpty(str))
            {
                return str;
            }
            else
            {
                return "无返回值";
            }
        }

        #endregion
    }

basic请求的两点:

1、将用户名和密码进行编码

2、设置请求头request.Headers.Add("Authorization", "Basic " + basic);

post请求注意点:

要设置request.ContentLength,以及将表单内容写入请求中,不然会出现411长度错误

如果都尝试了还是404,请再次检查地址的准确性,在上面坑了一天!!!!!!!!!

时间: 2024-10-13 11:55:16

c# post basic 接口的相关文章

Visual.Basic.6大学教程pdf

下载地址:网盘下载 内容简介 编辑 本书深入浅出地介绍了Visual Basic 6语言的基本概念和编程技术,包括对象.属性.方法.语句.函数.结构等基本问题,以及面向对象编程.数据库管理和网络编程等高级课题.全书共分为21章,系统地讨论了Visual Basic 6的编程技巧及应用,并且提供了大量实用和有趣的实例和习题.读者通过学习本书,可以在较短时间内掌握基本的和最新的程序设计技术.本书所配的"多媒体教室"光盘更是独具特色,通过交互式环境,使学习过程更加生动有趣. 目录 编辑 第1

总会有一个是你需要的

http://www.shouce.ren/post/d/id/112300 黑客攻防实战入门与提高.pdfhttp://www.shouce.ren/post/d/id/112299 黑客入门新手特训.pdfhttp://www.shouce.ren/post/d/id/112298 黑客与设计-剖析设计之美的秘密(彩印).pdfhttp://www.shouce.ren/post/d/id/112297 鸟哥的LINUX私房菜:服务器架设篇 (第二版).pdfhttp://www.shouc

hessian(转)

Hessian--轻量级远程调用方案 Hessian是caucho公司开发的一种基于二进制RPC协议(Remote Procedure Call protocol)的轻量级远程调用框架.具有多种语言的实现,但用的最多的当然是Java实现 :) Creating a Hessian service using Java has four steps: 1.Create an Java interface as the public API2.Create a client using Hessia

DBus学习笔记

摘要:DBus作为一个轻量级的IPC被越来越多的平台接受,在MeeGo中DBus也是主要的进程间通信方式,这个笔记将从基本概念开始记录笔者学习DBus的过程 [1] DBus学习笔记一:DBus学习的一些参考资料[2] DBus学习笔记二:什么是DBus?[3] DBus学习笔记三:DBus的一些基本概念 一些基本概念的解释和翻译:http://blog.mcuol.com/User/AT91RM9200/Article/12816_1.htmhttp://www.cnblogs.com/wzh

基于线上请求的性能测试系统CPC

1.背景 测试人员在设计性能测试脚本时,HTTP请求中的参数往往根据个人经验设置,而测试人员水平参差不齐,设计往往具有局限性,不够全面,不能涵盖全线上真实的请求,故得到的性能测试结果不能够真实反映线上真实的情况. 使用线上环境下的HTTP请求检查软件性能的问题,通过Gor记录线上真实的请求,作为性能测试脚本的请求池,用请求池物料进行性能测试,能真实的反映软件系统在线上环境下的性能指标和问题. 2.概念 2-1.架构图 2-2.技术栈 请求池: Gor: HTTP 录制工具 https://git

C#面向对象的基本概念 (Basic C# OOP Concept) 第三部分(多态,抽象类,虚方法,密封类,静态类,接口)

9.多态 Ploy的意思就是多于一种形式.在文章开始,方法那一章节就已经接触到了多态.多个方法名称相同,而参数不同,这就是多态的一种. 方法重载和方法覆盖就是用在了多态.多态有2中类型,一种是编译时多态,一种是运行时多态. 方法重载: 方法重载就是,多个方法拥有相同的方法名称,而参数个数或类型不同. 下面就是一个多态的例子,可以看到方法名称“BedRoom”被用到了2个方法中,就是2个方法有共同的方法名称"BedRoom",但是2个方法的参数是不同的. 1 class HouseOwn

Mac OSX (EI Capitan)搭建Caffe环境并配置python接口

Caffe是一个清晰而高效的深度学习框架,其作者是博士毕业于UC Berkeley的贾扬清.Caffe是纯粹的C++/CUDA架构,支持命令行.Python和MATLAB接口:可以在CPU和GPU直接无缝切换.我在MacbookPro(无NVIDIA显卡)上大费周章地配置了Caffe的环境,并花了许多时间配置其python接口. 一.下载Caffe github上的下载地址:https://github.com/BVLC/caffe进入到下载后的路径,并复制 Makefile.config.ex

NHibernate官方文档中文版--基础ORM(Basic O/R Mapping)

映射声明 对象/关系映射在XML文件中配置.mapping文件这样设计是为了使它可读性强并且可修改.mapping语言是以对象为中心,意味着mapping是围绕着持久化类声明来建立的,而不是围绕数据表. 要注意的是,尽管很多NHibernate使用者选择手动定义XML文件,但是仍然有很多工具可以用来生成mapping文件,包括NHibernate.Mapping.Attributes 库和各种各样基于模板的代码生成工具(CodeSmith, MyGeneration). 让我们用一个mappin

php mysql APP接口 移动端接口API &nbsp; M-API 开源代码

开源协议:Apache License 2.0 源码地址:https://github.com/movie0312/M-API.git M-API 概述... 1 一.    接口文档结构... 3 二.    接口环境设置... 3 1.   开发环境... 3 2.   生产环境... 3 三.    基本配置说明... 4 四.    mysql配置说明... 5 五.    对外接口入口配置说明... 7 六.    接口参数说明... 7 七.    code代码说明... 12