的与web服务器交互的HttpClient类,服务端与客户端定期电视发表机制

ca88会员登录中心

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
using System.Web;

假若大家要提供两个相当的小服务,采取HTTP协议进行广播发表,客户端 POST
一些数额到服务器上。客户端不必然是PC,更不自然会遵守1个Web
Form的格式来交给数据,它大概是三个周转在PC上的Desktop
Application,也恐怕是二个移动设备。

namespace Deerchao.Utility
{
    public class HttpClient
    {
        #region fields
        private bool keepContext;
        private string defaultLanguage = “zh-CN”;
        private Encoding defaultEncoding = Encoding.UTF8;
        private string accept = “*/*”;
        private string userAgent = “Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”;
        private HttpVerb verb = HttpVerb.GET;
        private HttpClientContext context;
        private readonly List<HttpUploadingFile> files = new
List<HttpUploadingFile>();
        private readonly Dictionary<string, string> postingData =
new Dictionary<string, string>();
        private string url;
        private WebHeaderCollection responseHeaders;
        private int startPoint;
        private int endPoint;
        #endregion

劳务器端接收如此的伸手极其简单,下面寥寥数行代码就能够完毕:

        #region events
        public event EventHandler<StatusUpdateEventArgs>
StatusUpdate;

在Web站点中新建1个Generic Handler(*.ashx),代码如下:

        private void
OnStatusUpdate(StatusUpdateEventArgs e)
        {
            EventHandler<StatusUpdateEventArgs> temp =
StatusUpdate;

[csharp]

            if (temp != null)
                temp(this, e);
        }
        #endregion

  1. <%@ WebHandler Language=”C#” Class=”Echo” %>
    1. using System;
  2. using System.Web;
  3. using System.IO;
    1. public class Echo : IHttpHandler
  4. {
  5. private System.Text.Encoding DefaultEncoding =
    System.Text.Encoding.UTF8;
    1. public void ProcessRequest (HttpContext context)
  6. {
  7. context.Response.ContentType = “text/plain”;
  8. context.Response.ContentEncoding = DefaultEncoding;
    1. Stream inputStream = context.Request.InputStream;
  9. using (StreamReader reader = new StreamReader(inputStream,
    DefaultEncoding))
  10. {
  11. string requestContent = reader.ReadToEnd();
  12. string responseContent = string.Format(“Received: {0} <== END”,
    requestContent);
    1. context.Response.Write(responseContent);
  13. }
  14. }
    1. public bool IsReusable
  15. {
  16. get { return false; }
  17. }
  18. }

        #region properties
        /// <summary>
        /// 是还是不是自动在分裂的呼吁间保留Cookie, Referer
        /// </summary>
        public bool KeepContext
        {
            get { return keepContext; }
            set { keepContext = value; }
        }

        /// <summary>
        /// 期望的回答的言语
        /// </summary>
        public string DefaultLanguage
        {
            get { return defaultLanguage; }
            set { defaultLanguage = value; }
        }

<%@ WebHandler Language="C#" Class="Echo" %>

using System;
using System.Web;
using System.IO;

public class Echo : IHttpHandler
{
    private System.Text.Encoding DefaultEncoding = System.Text.Encoding.UTF8;

    public void ProcessRequest (HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = DefaultEncoding;

        Stream inputStream = context.Request.InputStream;
        using (StreamReader reader = new StreamReader(inputStream, DefaultEncoding))
        {
            string requestContent = reader.ReadToEnd();
            string responseContent = string.Format("Received: {0} <== END", requestContent);

            context.Response.Write(responseContent);
        }
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

        /// <summary>
        ///
GetString()假诺不能够从HTTP头或Meta标签中获得编码音讯,则采取此编码来赢得字符串
        /// </summary>
        public Encoding DefaultEncoding
        {
            get { return defaultEncoding; }
            set { defaultEncoding = value; }
        }

下一场大家写2个轻便易行的客户端来测试它。在那一个客户端里大家贯彻了二个类HttpClient来举行HTTP
POST操作:

        /// <summary>
        /// 提醒发出Get请求照旧Post请求
        /// </summary>
        public HttpVerb Verb
        {
            get { return verb; }
            set { verb = value; }
        }

[csharp]

        /// <summary>
        /// 要上传的文件.假设不为空则自动转为Post请求
        /// </summary>
        public List<HttpUploadingFile> Files
        {
            get { return files; }
        }

1. //

  1. // Http protocol client.
  2. //

    1. namespace ConsoleClient
  3. {
  4. using System;
  5. using System.IO;
  6. using System.Net;
  7. using System.Text;
    1. /// <summary>
  8. /// Http protocol client.
  9. /// </summary>
  10. public class HttpClient
  11. {
  12. /// <summary>
  13. /// Post data to specific url and get response content.
  14. /// </summary>
  15. /// <param name=”url”>the url to post</param>
  16. /// <param name=”postData”>post data</param>
  17. /// <returns>response content</returns>
  18. public string Post(string url, string postData)
  19. {
  20. Uri uri = new Uri(url);
  21. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  22. request.Method = “POST”;
  23. request.ContentType = “application/x-www-form-urlencoded”;
    1. Encoding encoding = Encoding.UTF8;
  24. byte[] bytes = encoding.GetBytes(postData);
    1. request.ContentLength = bytes.Length;
    1. using (Stream writer = request.GetRequestStream())
  25. {
  26. writer.Write(bytes, 0, bytes.Length);
  27. writer.Close();
  28. }
    1. return this.ReadResponse(request);;
  29. }
    1. /// <summary>
  30. /// Read response content from http request result.
  31. /// </summary>
  32. /// <param name=”request”>http request object</param>
  33. /// <returns>response content.</returns>
  34. private string ReadResponse(HttpWebRequest request)
  35. {
  36. string result = string.Empty;
    1. using (HttpWebResponse response =
      (HttpWebResponse)request.GetResponse())
  37. {
  38. using (Stream responseStream = response.GetResponseStream())
  39. {
  40. using (StreamReader reader = new StreamReader(responseStream,
    Encoding.UTF8))
  41. {
  42. result = reader.ReadToEnd();
  43. reader.Close();
  44. }
  45. }
  46. }
    1. return result;
  47. }
  48. }
  49. }

// -----------------------------------------------------------------------

// Http protocol client.
// -----------------------------------------------------------------------

namespace ConsoleClient
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;

    /// <summary>
    /// Http protocol client.
    /// </summary>
    public class HttpClient
    {
        /// <summary>
        /// Post data to specific url and get response content.
        /// </summary>
        /// <param name="url">the url to post</param>
        /// <param name="postData">post data</param>
        /// <returns>response content</returns>
        public string Post(string url, string postData)
        {
            Uri uri = new Uri(url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            Encoding encoding = Encoding.UTF8;
            byte[] bytes = encoding.GetBytes(postData);

            request.ContentLength = bytes.Length;

            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(bytes, 0, bytes.Length);
                writer.Close();
            }

            return this.ReadResponse(request);;
        }

        /// <summary>
        /// Read response content from http request result.
        /// </summary>
        /// <param name="request">http request object</param>
        /// <returns>response content.</returns>
        private string ReadResponse(HttpWebRequest request)
        {
            string result = string.Empty;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                        reader.Close();
                    }
                }
            }

            return result;
        }
    }
}

然后大家如此就能够博得HTTP POST的归来:

[csharp]

  1. // Replace the string content with your actual address please.
  2. string defaultUrl =
    “”;
    1. HttpClient client = new HttpClient();
  3. string response = client.Post(defaultUrl, @”abc 123! 测试 @”);
    1. Console.OutputEncoding = System.Text.Encoding.UTF8;
  4. Console.WriteLine(response);

// Replace the string content with your actual address please.
string defaultUrl = "http://ServerName:8081/WebPath/AnyService.ashx";

HttpClient client = new HttpClient();
string response = client.Post(defaultUrl, @"abc 123! 测试 @");

Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine(response);

一经Client与Server两端都约定好利用某些格式对数码实行体系化与反类别化,举例都采纳Json,客户端把目的通过Json封装后Post给Server,Server再利用Json将对象从Json字符串中剖析出来,那样实行数据传递是有利的。再尽管大家要压缩传送出的数据量,那么能够开始展览gzip压缩与解压。又假如大家要思索安全性,那么我们得以在目的的布局中增添security
token举行验证,以及使用某种加密算法对字符串进行加密与解密。怎么表述就看您具体的行使了,创设二个属于你自个儿的轻量的service毫不费劲。

        /// <summary>
        /// 要发送的Form表单音信
        /// </summary>
        public Dictionary<string, string> PostingData
        {
            get { return postingData; }
        }

        /// <summary>
        /// 获取或设置请求能源的地点
        /// </summary>
        public string Url
        {
            get { return url; }
            set { url = value; }
        }

        /// <summary>
        /// 用于在获取回应后,暂且记录回应的HTTP头
        /// </summary>
        public WebHeaderCollection ResponseHeaders
        {
            get { return responseHeaders; }
        }

        /// <summary>
        /// 获取或设置期望的能源类型
        /// </summary>
        public string Accept
        {
            get { return accept; }
            set { accept = value; }
        }

        /// <summary>
        /// 获取或安装请求中的Http头User-Agent的值
        /// </summary>
        public string UserAgent
        {
            get { return userAgent; }
            set { userAgent = value; }
        }

        /// <summary>
        /// 获取或设置Cookie及Referer
        /// </summary>
        public HttpClientContext Context
        {
            get { return context; }
            set { context = value; }
        }

        /// <summary>
        /// 获取或安装获取内容的发轫点,用于断点续传,八线程下载等
        /// </summary>
        public int StartPoint
        {
            get { return startPoint; }
            set { startPoint = value; }
        }

        /// <summary>
        /// 获取或设置获取内容的结束点,用于断点续传,多下程下载等.
        /// 假如为0,表示收获能源从StartPoint开首的剩余内容
        /// </summary>
        public int EndPoint
        {
            get { return endPoint; }
            set { endPoint = value; }
        }

        #endregion

        #region constructors
        /// <summary>
        /// 构造新的HttpClient实例
        /// </summary>
        public HttpClient()
            : this(null)
        {
        }

        /// <summary>
        /// 构造新的HttpClient实例
        /// </summary>
        /// <param name=”url”>要赢得的能源的地方</param>
        public HttpClient(string url)
            : this(url, null)
        {
        }

        /// <summary>
        /// 构造新的HttpClient实例
        /// </summary>
        /// <param name=”url”>要获得的财富的地点</param>
        /// <param name=”context”>Cookie及Referer</param>
        public HttpClient(string url, HttpClientContext context)
            : this(url, context, false)
        {
        }

        /// <summary>
        /// 构造新的HttpClient实例
        /// </summary>
        /// <param name=”url”>要收获的财富的地点</param>
        /// <param name=”context”>Cookie及Referer</param>
        /// <param
name=”keepContext”>是还是不是自动在分化的央求间保留Cookie,
Referer</param>
        public HttpClient(string url, HttpClientContext context, bool
keepContext)
        {
            this.url = url;
            this.context = context;
            this.keepContext = keepContext;
            if (this.context == null)
                this.context = new HttpClientContext();
        }
        #endregion

        #region AttachFile
        /// <summary>
        /// 在央浼中增加要上传的公文
        /// </summary>
        /// <param
name=”fileName”>要上传的文本路线</param>
        /// <param name=”田野同志Name”>文件字段的称谓(也正是<input
type=file name=田野(field)Name>)里的田野同志Name)</param>
        public void AttachFile(string fileName, string fieldName)
        {
            HttpUploadingFile file = new HttpUploadingFile(fileName,
fieldName);
            files.Add(file);
        }

        /// <summary>
        /// 在伸手中增多要上传的公文
        /// </summary>
        /// <param name=”data”>要上传的文本内容</param>
        /// <param name=”fileName”>文件名</param>
        /// <param name=”田野Name”>文件字段的称呼(约等于<input
type=file name=田野先生Name>)里的田野(field)Name)</param>
        public void AttachFile(byte[] data, string fileName, string
fieldName)
        {
            HttpUploadingFile file = new HttpUploadingFile(data,
fileName, fieldName);
            files.Add(file);
        }
        #endregion

        /// <summary>
        /// 清空PostingData, Files, StartPoint, EndPoint,
ResponseHeaders, 并把Verb设置为Get.
        ///
在爆发叁个包罗上述音讯的伸手后,必须调用此方法或手工业安装相应属性以使下二遍呼吁不会遭到影响.
        /// </summary>
        public void Reset()
        {
            verb = HttpVerb.GET;
            files.Clear();
            postingData.Clear();
            responseHeaders = null;
            startPoint = 0;
            endPoint = 0;
        }

        private HttpWebRequest
CreateRequest()
        {
            HttpWebRequest req =
(HttpWebRequest)WebRequest.Create(url);
            req.AllowAutoRedirect = false;
            req.CookieContainer = new CookieContainer();
            req.Headers.Add(“Accept-Language”, defaultLanguage);
            req.Accept = accept;
            req.UserAgent = userAgent;
            req.KeepAlive = false;

            if (context.Cookies !=
null)
                req.CookieContainer.Add(context.Cookies);
            if (!string.IsNullOrEmpty(context.Referer))
                req.Referer = context.Referer;

            if (verb ==
HttpVerb.HEAD)
            {
                req.Method = “HEAD”;
                return req;
            }

            if (postingData.Count
> 0 || files.Count > 0)
                verb = HttpVerb.POST;

            if (verb ==
HttpVerb.POST)
            {
                req.Method = “POST”;

                MemoryStream
memoryStream = new MemoryStream();
                StreamWriter writer = new
StreamWriter(memoryStream);

                if (files.Count >
0)
                {
                    string newLine = “\r\n”;
                    string boundary =
Guid.NewGuid().ToString().Replace(“-“, “”);
                    req.ContentType = “multipart/form-data; boundary=” +
boundary;

                    foreach (string
key in postingData.Keys)
                    {
                        writer.Write(“–” + boundary + newLine);
                        writer.Write(“Content-Disposition: form-data;
name=\”{0}\”{1}{1}”, key, newLine);
                        writer.Write(postingData[key] + newLine);
                    }

                    foreach
(HttpUploadingFile file in files)
                    {
                        writer.Write(“–” + boundary + newLine);
                        writer.Write(
                            “Content-Disposition: form-data;
name=\”{0}\”; filename=\”{1}\”{2}”,
                            file.FieldName,
                            file.FileName,
                            newLine
                            );
                        writer.Write(“Content-Type:
application/octet-stream” + newLine + newLine);
                        writer.Flush();
                        memoryStream.Write(file.Data, 0,
file.Data.Length);
                        writer.Write(newLine);
                        writer.Write(“–” + boundary + newLine);
ca88会员登录中心,                    }
                }
                else
                {
                    req.ContentType =
“application/x-www-form-urlencoded”;
                    StringBuilder sb = new StringBuilder();
                    foreach (string key in postingData.Keys)
                    {
                        sb.AppendFormat(“{0}={1}&”,
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(postingData[key]));
                    }
                    if (sb.Length > 0)
                        sb.Length–;
                    writer.Write(sb.ToString());
                }

               
writer.Flush();

                using (Stream stream
= req.GetRequestStream())
                {
                    memoryStream.WriteTo(stream);
                }
            }

            if (startPoint != 0 &&
endPoint != 0)
                req.AddRange(startPoint, endPoint);
            else if (startPoint != 0 && endPoint == 0)
                req.AddRange(startPoint);

            return req;
        }

        /// <summary>
        /// 发出二遍新的请求,并重临获得的应对
        /// 调用此方法长久不会触发StatusUpdate事件.
        /// </summary>
        /// <returns>相应的HttpWebResponse</returns>
        public HttpWebResponse GetResponse()
        {
            HttpWebRequest req = CreateRequest();
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            responseHeaders = res.Headers;
            if (keepContext)
            {
                context.Cookies = res.Cookies;
                context.Referer = url;
            }
            return res;
        }

        /// <summary>
        /// 发出1次新的乞请,并重返回应内容的流
        /// 调用此措施永世不会触发StatusUpdate事件.
        /// </summary>
        /// <returns>蕴涵回应主体内容的流</returns>
        public Stream GetStream()
        {
            return GetResponse().GetResponseStream();
        }

        /// <summary>
        /// 发出一回新的央浼,并以字节数组格局重返回应的故事情节
        /// 调用此方法会触发StatusUpdate事件
        /// </summary>
        /// <returns>包涵回应主体内容的字节数组</returns>
        public byte[] GetBytes()
        {
            HttpWebResponse res = GetResponse();
            int length = (int)res.ContentLength;

            MemoryStream
memoryStream = new MemoryStream();
            byte[] buffer = new byte[0x100];
            Stream rs = res.GetResponseStream();
            for (int i = rs.Read(buffer, 0, buffer.Length); i > 0; i
= rs.Read(buffer, 0, buffer.Length))
            {
                memoryStream.Write(buffer, 0, i);
                OnStatusUpdate(new
StatusUpdateEventArgs((int)memoryStream.Length, length));
            }
            rs.Close();

            return
memoryStream.ToArray();
        }

        /// <summary>
        /// 发出3次新的请求,以Http头,或Html
Meta标签,或DefaultEncoding提醒的编码新闻对应对主体解码
        /// 调用此方法会触发StatusUpdate事件
        /// </summary>
        /// <returns>解码后的字符串</returns>
        public string GetString()
        {
            byte[] data = GetBytes();
            string encodingName = GetEncodingFromHeaders();

            if (encodingName ==
null)
                encodingName = GetEncodingFromBody(data);

            Encoding encoding;
            if (encodingName == null)
                encoding = defaultEncoding;
            else
            {
                try
                {
                    encoding = Encoding.GetEncoding(encodingName);
                }
                catch (ArgumentException)
                {
                    encoding = defaultEncoding;
                }
            }
            return encoding.GetString(data);
        }

        /// <summary>
        /// 发出贰回新的请求,对应对的主脑内容以钦定的编码进行解码
        /// 调用此方法会触发StatusUpdate事件
        /// </summary>
        /// <param name=”encoding”>钦命的编码</param>
        /// <returns>解码后的字符串</returns>
        public string GetString(Encoding encoding)
        {
            byte[] data = GetBytes();
            return encoding.GetString(data);
        }

        private string
GetEncodingFromHeaders()
        {
            string encoding = null;
            string contentType = responseHeaders[“Content-Type”];
            if (contentType != null)
            {
                int i = contentType.IndexOf(“charset=”);
                if (i != -1)
                {
                    encoding = contentType.Substring(i + 8);
                }
            }
            return encoding;
        }

        private string
GetEncodingFromBody(byte[] data)
        {
            string encodingName = null;
            string dataAsAscii = Encoding.ASCII.GetString(data);
            if (dataAsAscii != null)
            {
                int i = dataAsAscii.IndexOf(“charset=”);
                if (i != -1)
                {
                    int j = dataAsAscii.IndexOf(“\””, i);
                    if (j != -1)
                    {
                        int k = i + 8;
                        encodingName = dataAsAscii.Substring(k, (j – k)

  • 1);
                            char[] chArray = new char[2] { ‘>’, ‘”‘
    };
                            encodingName = encodingName.TrimEnd(chArray);
                        }
                    }
                }
                return encodingName;
            }

        /// <summary>
        /// 发出1次新的Head请求,获取财富的长度
        /// 此请求会忽略PostingData, Files, StartPoint, EndPoint, Verb
        /// </summary>
        /// <returns>重返的财富长度</returns>
        public int HeadContentLength()
        {
            Reset();
            HttpVerb lastVerb = verb;
            verb = HttpVerb.HEAD;
            using (HttpWebResponse res = GetResponse())
            {
                verb = lastVerb;
                return (int)res.ContentLength;
            }
        }

        /// <summary>
        /// 发出叁次新的乞求,把应对的基本点内容保留到文件
        /// 调用此方法会触发StatusUpdate事件
        /// 假若内定的文件存在,它会被遮盖
        /// </summary>
        /// <param
name=”fileName”>要保存的公文路线</param>
        public void SaveAsFile(string fileName)
        {
            SaveAsFile(fileName, FileExistsAction.Overwrite);
        }

        /// <summary>
        /// 发出二遍新的请求,把回应的关键性内容保留到文件
        /// 调用此方法会触发StatusUpdate事件
        /// </summary>
        /// <param
name=”fileName”>要封存的文书路线</param>
        /// <param
name=”existsAction”>钦赐的文书存在时的选项</param>
        /// <returns>是或不是向目的文件写入了数据</returns>
        public bool SaveAsFile(string fileName, FileExistsAction
existsAction)
        {
            byte[] data = GetBytes();
            switch (existsAction)
            {
                case FileExistsAction.Overwrite:
                    using (BinaryWriter writer = new BinaryWriter(new
FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)))
                        writer.Write(data);
                    return true;

                case
FileExistsAction.Append:
                    using (BinaryWriter writer = new BinaryWriter(new
FileStream(fileName, FileMode.Append, FileAccess.Write)))
                        writer.Write(data);
                    return true;

                default:
                    if (!File.Exists(fileName))
                    {
                        using (
                            BinaryWriter writer =
                                new BinaryWriter(new
FileStream(fileName, FileMode.Create, FileAccess.Write)))
                            writer.Write(data);
                        return true;
                    }
                    else
                    {
                        return false;
                    }
            }
        }
    }

    public class HttpClientContext
    {
        private CookieCollection cookies;
        private string referer;

        public CookieCollection
Cookies
        {
            get { return cookies; }
            set { cookies = value; }
        }

        public string Referer
        {
            get { return referer; }
            set { referer = value; }
        }
    }

    public enum HttpVerb
    {
        GET,
        POST,
        HEAD,
    }

    public enum FileExistsAction
    {
        Overwrite,
        Append,
        Cancel,
    }

    public class HttpUploadingFile
    {
        private string fileName;
        private string fieldName;
        private byte[] data;

        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }

        public string FieldName
        {
            get { return fieldName; }
            set { fieldName = value; }
        }

        public byte[] Data
        {
            get { return data; }
            set { data = value; }
        }

        public
HttpUploadingFile(string fileName, string fieldName)
        {
            this.fileName = fileName;
            this.fieldName = fieldName;
            using (FileStream stream = new FileStream(fileName,
FileMode.Open))
            {
                byte[] inBytes = new byte[stream.Length];
                stream.Read(inBytes, 0, inBytes.Length);
                data = inBytes;
            }
        }

        public
HttpUploadingFile(byte[] data, string fileName, string fieldName)
        {
            this.data = data;
            this.fileName = fileName;
            this.fieldName = fieldName;
        }
    }

    public class
StatusUpdateEventArgs : EventArgs
    {
        private readonly int bytesGot;
        private readonly int bytesTotal;

        public
StatusUpdateEventArgs(int got, int total)
        {
            bytesGot = got;
            bytesTotal = total;
        }

        /// <summary>
        /// 已经下载的字节数
        /// </summary>
        public int BytesGot
        {
            get { return bytesGot; }
        }

        /// <summary>
        /// 能源的总字节数
        /// </summary>
        public int BytesTotal
        {
            get { return bytesTotal; }
        }
    }
}
.Net类Curry提供了HttpWebRequest等类,方便我们编制程序与Web服务器实行交互.
但是实际上使用中大家常常会遇上以下须要,基础类里未有平昔提供对应的职能(WebClient类富含这一个意义,只是用起来有一些麻烦一点–谢谢网民东吴居士的提醒):

  • 对HttpWebResponse获取的HTML进行理文件字编码转变,使之不会冒出乱码;
  • 自动在Session间保证Cookie,Referer等城门失火音讯;
  • 宪章HTML表单提交;
  • 向服务器上传文件;
  • 对2进制的能源,直接获得再次来到的字节数组(byte[]),或许封存为文件

为精晓决这么些主题材料,作者付出了HttpClient类.上面是选取的方法:

  • 赢得编码转变后的字符串

    HttpClient client=new HttpClient(url);
    string html=client.GetString();

    GetString()函数内部会寻觅Http Headers,
    以及HTML的Meta标签,试图找寻获取的内容的编码音信.假如都找不到,它会采纳client.DefaultEncoding,
    这几个属性默以为utf-8, 也足以手动设置.

  • 机动保持Cookie, Referer

    HttpClient client=new HttpClient(url1, null, true);
    string html1=client.GetString();
    client.Url=url2;
    string html2=client.GetString();

    这里HttpClient的第多少个参数,keepContext设置为真时,HttpClient会自动记录每一遍交互时服务器对Cookies举办的操作,同时会此前三次呼吁的Url为Referer.在那几个例子里,获取html二时,会把url一作为Referer,
    同时会向服务器传递在收获html一时服务器设置的Cookies.
    当然,你也能够在协会HttpClient时直接提供第贰回呼吁要发生的Cookies与Referer:

    HttpClient client=new HttpClient(url, new WebContext(cookies,
    referer), true);

    要么,在采用进程中随时随地修改这么些音讯:

    client.Context.Cookies=cookies;
    client.Context.referer=referer;

  • 效仿HTML表单提交

    HttpClient client=new HttpClient(url);
    client.PostingData.Add(fieldName1, filedValue1);
    client.PostingData.Add(fieldName2, fieldValue2);
    string html=client.GetString();

    地点的代码相当于付出了1个有七个input的表单.
    在PostingData非空,也许附加了要上传的公文时(请看下边包车型大巴上传和文件),
    HttpClient会自动把HttpVerb改成POST, 并将相应的新闻附加到Request上.

  • 向服务器上传文件

    HttpClient client=new HttpClient(url);
    client.AttachFile(fileName, fieldName);
    client.AttachFile(byteArray, fileName, fieldName);
    string html=client.GetString();

    这几个中的田野同志Name相当于<input type=”file” name=”田野Name”
    />里的田野同志Name. fileName当然就是您想要上传的文本路线了.
    你也能够一贯提供3个byte[] 作为文件内容,
    但纵然如此,你也必须提供一个文本名,以满意HTTP标准的须要.

  • 今非昔比的回到形式

    字符串: string html = client.GetString();
    流: Stream stream = client.GetStream();
    字节数组: byte[] data = client.GetBytes();
    保留到文件:  client.SaveAsFile(fileName);
    也许,你也足以向来操作HttpWebResponse: HttpWebResponse res =
    client.GetResponse();

    每调用三回上述任何一个办法,都会招致发生贰个HTTP Request,
    也正是说,你不可能而且获得有个别Response的三种回到格局.
    其它,调用后它们大四一个随后,你能够由此client.ResponseHeaders来博取服务器再次回到的HTTP头.

  • 下载能源的钦点部分(用于断点续传,十二线程下载)

    HttpClient client=new HttpClient(url);
    //发出HEAD请求,获取能源长度
    int length=client.HeadContentLength();

    //只收获后1/贰剧情
    client.StartPoint=length/2;
    byte[] data=client.GetBytes();

    HeadContentLength()只会生出HTTP HEAD请求.依据HTTP协议,
    HEAD与GET的功效一样, 可是,只回去HTTP头,而不回去财富入眼内容.
    也便是说,用那一个点子,你没办法获取二个索要经过POST技艺获取的财富的长短,借令你真正有那般的急需,提出您能够因此GetResponse(),然后从ResponseHeader里获取Content-Length.

安排中还有其余一些功效要加进去,比如断点续传, 四线程下载,
下载进度更新的轩然大波机制等,
正在思量什么与未来的代码融入到1块儿,期待您的反馈.

 

注意:行使时应有加上对System.Web.dll的引用,并在行使此类的代码前增加”using
System.Web;”,不然会不可能透过编写翻译.

作品来源:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图