博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
向服务器发送Post或Get请求(封装好的)
阅读量:5041 次
发布时间:2019-06-12

本文共 7786 字,大约阅读时间需要 25 分钟。

 

///         /// 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
集合遍历成URL参数! ///
/// Dictionary
config ///
Query
public static string BuildQueryString(Dictionary
config) { 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 Task
Request (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; } } }

  

 

转载于:https://www.cnblogs.com/BounceGuo/p/10076215.html

你可能感兴趣的文章
问题集锦
查看>>
设置tomcat内存设定
查看>>
Django:中间件与csrf
查看>>
Access specifier 访问限定词
查看>>
js怎么获取动态链式属性呢?
查看>>
【python进阶】Garbage collection垃圾回收1
查看>>
调度系统任务创建---创建一个JoinTrigger的依赖任务(五)
查看>>
Leetcode-Read N Characters Given Read4
查看>>
九年程序人生 总结分享
查看>>
Balanced Lineup
查看>>
C语言:数据类型
查看>>
C# string和byte[]数组之间相互转换
查看>>
无论多累,都要坚持下去!
查看>>
[转载]Linux 线程实现机制分析
查看>>
各 Android 平台版本支持的 API 级别
查看>>
PHP学习 Object Oriented 面向对象 OO
查看>>
转载 .net中的dll.refresh文件和pdb文件
查看>>
python 缩进问题
查看>>
黑马程序员 一个准程序的内心告白,原来上帝是那么的遥远
查看>>
铺地毯
查看>>