123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217 |
- using Bowin.Common.JSON;
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- namespace Bowin.Common
- {
- public class HttpClient
- {
- #region //字段
- private ArrayList bytesArray;
- private Encoding encoding = Encoding.UTF8;
- private string boundary = String.Empty;
- private WebHeaderCollection headers = new WebHeaderCollection();
- #endregion
- #region //构造方法
- public HttpClient()
- {
- bytesArray = new ArrayList();
- string flag = DateTime.Now.Ticks.ToString("x");
- boundary = "---------------------------" + flag;
- headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
- }
- #endregion
- #region //方法
- /// <summary>
- /// 合并请求数据
- /// </summary>
- /// <returns></returns>
- private byte[] MergeContent()
- {
- int length = 0;
- int readLength = 0;
- 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;
- }
- public bool Download(String requestUrl, Dictionary<string, string> parameters, out String responseText)
- {
- WebClient webClient = new WebClient();
- if (this.headers != null && this.headers.Count > 0)
- {
- webClient.Headers = this.headers;
- }
- string fullUrl = requestUrl;
-
- for (int i = 0; i < parameters.Count; i++)
- {
- if (i == 0 && !requestUrl.Contains("?"))
- {
- fullUrl += "?";
- }
- else
- {
- fullUrl += "&";
- }
- fullUrl += parameters.Keys.ElementAt(i) + "=" + parameters.Values.ElementAt(i);
- }
- var response = new byte[0];
- try
- {
- response = webClient.DownloadData(fullUrl);
- responseText = System.Text.Encoding.UTF8.GetString(response);
- return true;
- }
- catch (WebException ex)
- {
- Stream responseStream = ex.Response.GetResponseStream();
- response = new byte[ex.Response.ContentLength];
- responseStream.Read(response, 0, response.Length);
- }
- responseText = System.Text.Encoding.UTF8.GetString(response);
- return false;
- }
- /// <summary>
- /// 上传
- /// </summary>
- /// <param name="requestUrl">请求url</param>
- /// <param name="responseText">响应</param>
- /// <returns></returns>
- public bool Upload(String requestUrl, out String responseText)
- {
- WebClient webClient = new WebClient();
- if (this.headers != null && this.headers.Count > 0)
- {
- webClient.Headers = this.headers;
- var contentType = webClient.Headers.AllKeys.Where(x => x.ToLower() == "content-type").Select(x => webClient.Headers[x]).FirstOrDefault();
- if (contentType != null)
- {
- if (!contentType.TrimEnd().EndsWith(";"))
- {
- contentType += ";";
- }
- contentType += "boundary=" + boundary;
- webClient.Headers.Set("Content-Type", contentType);
- }
- else
- {
- webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
- }
- }
- byte[] responseBytes;
- byte[] bytes = MergeContent();
- try
- {
- responseBytes = webClient.UploadData(requestUrl, 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, 0, responseBytes.Length);
- }
- responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
- return false;
- }
- public void SetHeaders(WebHeaderCollection headers)
- {
- if (this.headers != null && headers != null && headers.Count > 0)
- {
- this.headers = headers;
- }
- }
- /// <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(FormFile formFile)
- {
- 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, formFile.FieldName, formFile.Filename, formFile.ContentType);
- byte[] headerBytes = encoding.GetBytes(httpRowData);
- byte[] endBytes = encoding.GetBytes(end);
- byte[] fileDataBytes = new byte[headerBytes.Length + formFile.FileBytes.Length + endBytes.Length];
- headerBytes.CopyTo(fileDataBytes, 0);
- formFile.FileBytes.CopyTo(fileDataBytes, headerBytes.Length);
- endBytes.CopyTo(fileDataBytes, headerBytes.Length + formFile.FileBytes.Length);
- bytesArray.Add(fileDataBytes);
- }
- #endregion
- public static Dictionary<string, string> GetFromCollections<T>(T source) where T : class
- {
- JObject sourceObj = source.ToJson().ToObject<JObject>();
- Dictionary<string, string> result = new Dictionary<string, string>();
- foreach (var key in sourceObj.Properties())
- {
- result.Add(key.Name, key.Value.Value<string>());
- }
- return result;
- }
- }
- public class FormFile
- {
- public string FieldName { get; set; }
- public string Filename { get; set; }
- public string ContentType { get; set; }
- public Byte[] FileBytes { get; set; }
- }
- }
|