1. 使用HttpClient

前面拼接StringContent

 string strContent = "client_id=client&client_secret=secret&grant_type=client_credentials";
            HttpContent content = new StringContent(strContent, Encoding.UTF8, "application/x-www-form-urlencoded");

使用await:

public async void GetResponse()
        {
            HttpClient client = new HttpClient();
            Url = "http://xxxx";
            ClientInfo info = new ClientInfo();
            Json = JsonConvert.SerializeObject(info, Settings);
            HttpContent content = new StringContent(Json, Encoding.UTF8, "application/json");
            using (var response = await client.PostAsync(Url, content))
            {
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
        }

这里可判断请求的状态

var content = await client.PostAsync("http://localhost:5001/api/values/",httpContent);
                switch (content.StatusCode)
                {
                    case HttpStatusCode.OK:
                        Console.WriteLine(content.Content.ReadAsStringAsync().Result);
                        break;
                    case HttpStatusCode.Unauthorized:
                        //todo:重新申请token
                        break;
                }

不使用await:

/// <summary>
        /// 将GET请求发送到指定URI
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <returns>返回字符串</returns>
        public static string HttpGet(string url)
        {
            string str = string.Empty;
            using (HttpClient client = new HttpClient())
            {
                using (var response = client.GetAsync(url))
                {
                    response.Result.EnsureSuccessStatusCode();
                    str = response.Result.Content.ReadAsStringAsync().Result;
                }
            }
            return str;
        }

需要认证的:

/// <summary>
        /// 将GET请求发送到有身份验证的指定URI
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <param name="user">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>返回字符串</returns>
        public static string HttpGet(string url, string user, string password)
        {
            string str = string.Empty;
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential(user, password);
            using (HttpClient client = new HttpClient(handler))
            {
                using (var response = client.GetAsync(url))
                {
                    response.Result.EnsureSuccessStatusCode();
                    str = response.Result.Content.ReadAsStringAsync().Result;
                }
            }
            return str;
        }

Post请求:

/// <summary>
        /// 将POST请求发送到指定URI
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <param name="content">正文(JSON)</param>
        /// <returns>返回字符串</returns>
        public static string HttpPost(string url, string content)
        {
            string str = string.Empty;
            HttpContent httpcontent = new StringContent(content, Encoding.UTF8, "application/json");
            using (HttpClient client = new HttpClient())
            {
                using (var response = client.PostAsync(url, httpcontent))
                {
                  response.Result.EnsureSuccessStatusCode();
                  str = response.Result.Content.ReadAsStringAsync().Result;
                }
            }
            return str;
        }

需要认证的:

/// <summary>
        /// 将POST请求发送到有身份验证的指定URI
        /// </summary>
        /// <param name="url">链接地址</param>
        /// <param name="content">正文(JSON)</param>
        /// <param name="user">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>返回字符串</returns>
        public static string HttpPost(string url, string content, string user, string password)
        {
            string str = string.Empty;
            HttpClientHandler handler = new HttpClientHandler();
            handler.Credentials = new NetworkCredential(user, password);
            HttpContent httpcontent = new StringContent(content, Encoding.UTF8, "application/json");
            using (HttpClient client = new HttpClient(handler))
            {
                if (url.Contains("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    ServicePointManager.Expect100Continue = false;
                }
                using (var response = client.PostAsync(url, httpcontent))
                {
                    response.Result.EnsureSuccessStatusCode();
                    str = response.Result.Content.ReadAsStringAsync().Result;
                }
            }
            return str;
        }

2.使用HttpWebRequest

Get请求:

/// <summary>
        /// 访问相关地址,并获取访问结果。
        /// </summary>
        /// <param name="url">连接地址。</param>
        /// <returns>返回字符串。</returns>
        public static string HttpRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "Get";
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            )
            {
                encoding = "UTF-8"; //默认编码
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            return reader.ReadToEnd();
        }

需要认证的Get请求:

/// <summary>
        /// 访问相关地址,并获取访问结果。
        /// </summary>
        /// <param name="url">连接地址。</param>
        /// <param name="user">用户名。</param>
        /// <param name="password">密码。</param>
        /// <returns>返回字符串。</returns>
        public static string HttpRequest(string url, string user, string password)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Credentials = new NetworkCredential(user, password);
            request.Method = "Get";
            request.ContentType = "application/json";
            request.KeepAlive = false;
            request.Accept = "*/*";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            )
            {
                encoding = "UTF-8"; //默认编码
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            return reader.ReadToEnd();
        }

Post:

string url = "https://xxx.xx.xxx.xxx:xx/gateway/file";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.Expect100Continue = false;
            request.Method = "Post";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "application/octet-stream";
            request.Timeout =  *  * ;

            string param = "callerIp=8.8.8.8&charset=utf-8&language=zh_CN&merchantId=xxx";
            byte[] data = Encoding.UTF8.GetBytes(param);
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(data, , data.Length);
            }
            Encoding encoding = Encoding.UTF8;
            string responseData = String.Empty;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }
            }

使用此方法需要注意参数需要HttpUtility.UrlEncode

/// <summary>
        /// 将POST请求发送到指定URI
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="content">内容</param>
        /// <param name="contentType">MIME类型</param>
        /// <param name="encode">编码</param>
        /// <param name="timeOut">超时时间(单位:毫秒)</param>
        /// <returns>响应内容</returns>
        )
        {
            string result = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            if (url.Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                ServicePointManager.Expect100Continue = false;
            }
            request.Method = "Post";
            request.ContentType = contentType;
            request.Timeout = timeOut;
            byte[] data = encode.GetBytes(content);
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(data, , data.Length);
            }
            var responseStream = request.GetResponse().GetResponseStream();
            using (var response = request.GetResponseAsync())
            {
                var stream = response.Result.GetResponseStream();
                using (StreamReader sr = new StreamReader(stream))
                {
                    result = sr.ReadToEnd();
                }
            }
            return result;
        }

3.使用WebClient:

不使用Json:

/// <summary>
        /// 将POST请求发送到指定URI
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="collection">参数集合</param>
        /// <returns>字符串</returns>
        public static string HttpPost(string url, System.Collections.Specialized.NameValueCollection collection)
        {
            string result = string.Empty;
            using (WebClient client = new WebClient())
            {
                byte[] response = client.UploadValues(url, collection);
                result = Encoding.UTF8.GetString(response);
            }
            return result;
        }

同时上传文件和表单内容:

public class HttpRequestClient
    {
        #region //字段
        private ArrayList bytesArray;
        private Encoding encoding = Encoding.UTF8;
        private string boundary = String.Empty;
        #endregion

        #region //构造方法
        public HttpRequestClient()
        {
            bytesArray = new ArrayList();
            string flag = DateTime.Now.Ticks.ToString("x");
            boundary = "---------------------------" + flag;
        }
        #endregion

        #region //方法
        /// <summary>
        /// 合并请求数据
        /// </summary>
        /// <returns></returns>
        private byte[] MergeContent()
        {
            ;
            ;
            string endBoundary = "--" + boundary + "--\r\n";
            byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);

            bytesArray.Add(endBoundaryBytes);

            foreach (byte[] b in bytesArray)
            {
                length += b.Length;
            }

            byte[] bytes = new byte[length];

            foreach (byte[] b in bytesArray)
            {
                b.CopyTo(bytes, readLength);
                readLength += b.Length;
            }

            return bytes;
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="requestUrl">请求url</param>
        /// <param name="responseText">响应</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool Upload(String requestUrl, out String responseText, string username, string password)
        {
            WebClient webClient = new WebClient();
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                webClient.Credentials = new NetworkCredential(username, password);
            }
            webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
            if (requestUrl.Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                ServicePointManager.Expect100Continue = false;
            }
            byte[] responseBytes;
            byte[] bytes = MergeContent();

            try
            {
                responseBytes = webClient.UploadData(requestUrl, "POST", bytes);
                responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
                return true;
            }
            catch (WebException ex)
            {
                Stream responseStream = ex.Response.GetResponseStream();
                responseBytes = new byte[ex.Response.ContentLength];
                responseStream.Read(responseBytes, , responseBytes.Length);
            }
            responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
            return false;
        }

        /// <summary>
        /// 设置表单数据字段
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        /// <returns></returns>
        public void SetFieldValue(String fieldName, String fieldValue)
        {
            string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
            string httpRowData = String.Format(httpRow, fieldName, fieldValue);

            bytesArray.Add(encoding.GetBytes(httpRowData));
        }

        /// <summary>
        /// 设置表单文件数据
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="filename">字段值</param>
        /// <param name="contentType">内容内型</param>
        /// <param name="fileBytes">文件字节流</param>
        /// <returns></returns>
        public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
        {
            string end = "\r\n";
            string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string httpRowData = String.Format(httpRow, fieldName, filename, contentType);

            byte[] headerBytes = encoding.GetBytes(httpRowData);
            byte[] endBytes = encoding.GetBytes(end);
            byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length];

            headerBytes.CopyTo(fileDataBytes, );
            fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
            endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length);

            bytesArray.Add(fileDataBytes);
        }

        public string GetAuthorization(string username, string password)
        {
            string authorization = string.Format("{0}:{1}", username, password);

            return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
        }
        #endregion
    }

调用方法:

 string responseText = "";
                Stream fs = file.InputStream;
                byte[] fileBytes = new byte[file.ContentLength];
                fs.Read(fileBytes, , file.ContentLength);
                fs.Close(); fs.Dispose();
                HttpRequestClient httpRequestClient = new HttpRequestClient();
                httpRequestClient.SetFieldValue("file", Path.GetFileName(file.FileName), "application/octet-stream", fileBytes);
                if (httpRequestClient.Upload(uri, out responseText, threadUserName, threadPassword))
                {
                    //dosomething
                }
                else
                {
                    context.Response.Write("上传失败" );
                }

采用异步发送但同步接收:

/// <summary>
        /// 将POST请求发送到指定URI
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="collection">参数集合</param>
        /// <param name="contentType">MIME类型</param>
        /// <param name="acceptType">接收类型</param>
        /// <returns>字节数组</returns>
        public static byte[] HttpPost(string url, System.Collections.Specialized.NameValueCollection collection, string contentType,string acceptType)
        {
            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Content-Type", contentType);
                client.Headers.Add("Accept", acceptType);
                if (url.Contains("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    ServicePointManager.Expect100Continue = false;
                }
                using (var response = client.UploadValuesTaskAsync(url, collection))
                {
                    byte[] result= response.Result;
                    return result;
                }
            }
        }

下载文件:

/// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="fileName">路径</param>
        public static void DownloadFile(string url,string fileName)
        {
            WebClient client = new WebClient();
            client.DownloadFile(url, fileName);
        }

使用这个方法下载文件拿不到原来的文件名,可以改用下面的方法:

using (HttpClient client = new HttpClient())
            {
                using (var response = client.GetAsync(url))
                {
                    response.Result.EnsureSuccessStatusCode();
                    var name = response.Result.Content.Headers.ContentDisposition.FileName.Replace("\"", "");
                    var buff = response.Result.Content.ReadAsByteArrayAsync().Result;
                    string filename = Path.Combine(path, name);
                    using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate))
                    {
                        fs.Write(buff, , buff.Length);
                    }
                }
            }

程序模拟HTTP请求的更多相关文章

  1. python_程序模拟浏览器请求及会话保持

    python下读取一个页面的数据可以通过urllib2轻松实现请求 import urllib2 print urllib2.urlopen('http://www.baidu.com').read( ...

  2. 程序模拟浏览器请求及会话保持-python实现

    http://www.cnblogs.com/zxlovenet/p/4006649.html

  3. .Net(c#)模拟Http请求之HttpWebRequest封装

    一.需求: 向某个服务发起请求获取数据,如:爬虫,采集. 二.步骤(HttpWebRequest): 无非在客户端Client(即程序)设置请求报文(如:Method,Content-Type,Age ...

  4. 使用 jQuery Mockjax 插件模拟 Ajax 请求

    在实际的开发过程中,前端后台协商好了统一的接口,就各自开始自己的任务了.这时候我有这么一个 Ajax 请求需要从后台获取数据: $.ajax({ url: '/products/' }).done(f ...

  5. 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView

    本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...

  6. python模拟http请求2

    发现了一个非常好用的第三方module:requests,模拟接口非常简单. 详细了解请移步:http://docs.python-requests.org/en/latest/ 非常不错 #!cod ...

  7. python模拟http请求

    下文主要讲述如何利用python自带的库模拟http请求,为以后利用python做API测试做准备. 只讲述模拟http的过程,具体到自己用的时候,要以自己的应用为准做出适当的调整. #!coding ...

  8. 使用 HttpWebRequest 发送模拟 POST 请求

    使用HttpWebRequest发送模拟POST请求  网页中,如果form的method="POST",这时点击submit按钮可以给服务器发送了一个POST请求,如果metho ...

  9. WCF技术剖析之一:通过一个ASP.NET程序模拟WCF基础架构

    原文:WCF技术剖析之一:通过一个ASP.NET程序模拟WCF基础架构 细算起来,已经有好几个月没有真正的写过文章了.近半年以来,一直忙于我的第一本WCF专著<WCF技术剖析>的写作,一直 ...

随机推荐

  1. DataFrame按行读取:DataFrame之values

    http://blog.csdn.net/u014607457/article/details/51290582 def fill_core(self): RatingTable=pd.read_cs ...

  2. Android类装载器DexClassLoader的简单使用-----制作android插件的前奏

    声明:此篇文章借鉴<android内核剖析>整理得来. 一.装载器简介 “类装载器”(ClassLoader),顾名思义,就是用来动态装载class文件的.标准的Java SDK中有个Cl ...

  3. Android-intent.addFlags-Activity启动模式

    之前写的Android-Activity启动模式(launchMode),Android-Activity启动模式-应用场景,讲解的都是在AndroidManifest.xml配置launchMode ...

  4. [LeetCode 总结帖]: 链表专题

    链表在笔试面试中都是出镜率极高的一种数据结构. 由于链表具有结构简单,代码量较少,变化多,可以较为全面的考察应聘者的逻辑思考能力以及应变能力的特点,而备受面试官青睐. 在本节中,我将Leetcode中 ...

  5. vsftpd 常见问题

    一.vsftp服务能开启却连接不上的解决办法: 用虚拟机装了centos,vsftp是用centos自带的.启动vsftd服务后却一直连不上,原因是被防火墙给挡了. 查看防火墙状态:/etc/init ...

  6. (zxing.net)一维码MSI的简介、实现与解码

    一.简介 MSI/Plessey 条码(也被称为 MSI 或 Modified Plessey)是一款数字条码,多用于超市.存储用的仓库和其他贮藏室的货架.货架上的条码可以告知货架上的产品.应放数量和 ...

  7. BitAdminCore框架更新日志20180516

    前言 经过多次的重构,目前BitAdminCore框架已经基本上稳定,近期对代码进行多次重构,让代码保持更整洁. 为促进框架的推广,更好的实现价值分享,即日起推出更新日志系列,每次更新内容进行描述. ...

  8. TensorFlow从1到2(十)带注意力机制的神经网络机器翻译

    基本概念 机器翻译和语音识别是最早开展的两项人工智能研究.今天也取得了最显著的商业成果. 早先的机器翻译实际脱胎于电子词典,能力更擅长于词或者短语的翻译.那时候的翻译通常会将一句话打断为一系列的片段, ...

  9. 五,session数据写入memcached

    1,session数据通常保存在服务器端的文件中,它的默认过期时间是1440s.我们可以将session数据保存到memcached中,设定memcached的过期时间大于session过期时间即可. ...

  10. java实现fp-growth算法

    本文参考韩家炜<数据挖掘-概念与技术>一书第六章,前提条件要理解 apriori算法. 另外一篇写得较好的文章在此推荐: http://hi.baidu.com/nefzpohtpndho ...