////// Web请求方式:1、Get 2、Post /// public enum RequestMethod { Get, Post }
////// 保存图片 /// /// ///private static string SaveImage(HttpPostedFileBase uploadfile, string filePath) { string fileExtentsion = Path.GetExtension(uploadfile.FileName).ToLower(); string tmpFileName = Guid.NewGuid().ToString("N").ToLower() + fileExtentsion; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string serverLocalPath = Path.Combine(filePath, tmpFileName); uploadfile.SaveAs(serverLocalPath); return serverLocalPath; }
////// Web请求 /// /// /// /// ///public static string Request(string url, RequestMethod method, Dictionary parameters) { UriBuilder URI = new UriBuilder(url); HttpWebRequest webRequest = null; Stream requestWriter = null; string responseData = BuildQueryString(parameters); URI.Query = responseData; webRequest = System.Net.WebRequest.Create(URI.Uri) as HttpWebRequest; webRequest.Method = method.ToString(); webRequest.ServicePoint.Expect100Continue = false; byte[] data = Encoding.UTF8.GetBytes(responseData); if (method == RequestMethod.Post) { webRequest.ContentType = "application/x-www-form-urlencoded"; requestWriter = webRequest.GetRequestStream(); try { requestWriter.Write(data, 0, data.Length); } catch { throw; } finally { requestWriter.Close(); requestWriter = null; } } responseData = WebResponseGet(webRequest); webRequest = null; return responseData; }
////// 当前请求转发至其他服务器(上传多张图片) /// /// /// /// ///public static string HttpUploadFileList(string url, RequestMethod method, Dictionary parameters, List uploadfileList) { string result = string.Empty; string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = method.ToString(); request.KeepAlive = true; request.Credentials = CredentialCache.DefaultCredentials; Stream stream = request.GetRequestStream(); string template = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; #region request.form 参数 foreach (string _key in parameters.Keys) { string value = Convert.ToString(parameters[_key]); stream.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(template, _key, value); byte[] formitembytes = Encoding.UTF8.GetBytes(formitem); stream.Write(formitembytes, 0, formitembytes.Length); } #endregion stream.Write(boundarybytes, 0, boundarybytes.Length); #region 文件 foreach (HttpPostedFileBase uploadfile in uploadfileList) { stream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, "uploadfile", uploadfile.FileName, uploadfile.ContentType); byte[] headerbytes = Encoding.UTF8.GetBytes(header); stream.Write(headerbytes, 0, headerbytes.Length); byte[] imageData = null; using (BinaryReader binaryReader = new BinaryReader(uploadfile.InputStream)) { imageData = binaryReader.ReadBytes(uploadfile.ContentLength); } stream.Write(imageData, 0, imageData.Length); } #endregion byte[] bytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); stream.Write(bytes, 0, bytes.Length); stream.Close(); result = WebResponseGet(request); request = null; return result; }
////// 读取数据 /// /// HttpWebRequest ///根据参数条件返回相应的数据 private static string WebResponseGet(HttpWebRequest webRequest) { StreamReader responseReader = null; string responseData = ""; try { responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); responseData = responseReader.ReadToEnd(); } catch { throw; } finally { webRequest.GetResponse().GetResponseStream().Close(); responseReader.Close(); responseReader = null; } return responseData; }
////// 将Dictionary /// Dictionary集合遍历成URL参数! /// config /// Query public static string BuildQueryString(Dictionaryconfig) { List paramList = new List (); foreach (KeyValuePair item in config) { paramList.Add(string.Format("{0}={1}", item.Key, item.Value)); } return string.Join("&", paramList.ToArray()); }
HttpClient发送数据:
public async TaskRequest (System.Net.Http.HttpMethod method, Dictionary keyValeDic, string url, HttpContent content) { using (HttpClient client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage(); request.Method = method; request.RequestUri = new Uri(url); request.Content = content; if (keyValeDic != null) { foreach(var keyVale in keyValeDic) { request.Headers.Add(keyVale.Key, keyVale.Value); } } if (content != null) { client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); } // 毫秒转 TimeSpan var milliseconds = 5 * 1000;//可配置 client.Timeout = TimeSpan.FromMilliseconds(milliseconds); HttpResponseMessage responseMessage = await client.SendAsync(request); string result = await responseMessage.Content.ReadAsStringAsync(); if (responseMessage.IsSuccessStatusCode) { return result; } else { return string.Empty; } } }