C# 发送Http协议 模拟 Post Get请求

 

1.参数 paramsValue的格式 要和 Reques.ContentType一致,

如果 contentype  "application/x-www-form-urlencoded" 表单类型,那么  参数为   a=1&b=2 形式

如果 。。。         "application/json"  json 类型  那么参数就为  "{a:1,b:2}" 格式

 

2.可以添加自定义header,  add(key,value)

接受获取header   Request.Headers.Get(key)

 

 public static string HttpGet(string url)
       { 
           string result=string.Empty;
           try
           {
               HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
               wbRequest.Method = "GET";
               HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
               using (Stream responseStream = wbResponse.GetResponseStream())
               {
                   using (StreamReader sReader = new StreamReader(responseStream))
                   {
                       result = sReader.ReadToEnd();
                   }
               }
           }
           catch (Exception ex)
           { 
           
           }
           return result;
       }
HttpGet
 public static string HttpPost(string url, string paramData, Dictionary<string, string> headerDic = null)
       {
           string result = string.Empty;
           try
           {
               HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
               wbRequest.Method = "POST";
               wbRequest.ContentType = "application/x-www-form-urlencoded";
               wbRequest.ContentLength = Encoding.UTF8.GetByteCount(paramData);
               if (headerDic != null && headerDic.Count > 0)
               {
                   foreach (var item in headerDic)
                   {
                       wbRequest.Headers.Add(item.Key, item.Value);
                   }
               }
               using (Stream requestStream = wbRequest.GetRequestStream())
               {
                   using (StreamWriter swrite = new StreamWriter(requestStream))
                   {
                       swrite.Write(paramData);
                   }
               }
               HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
               using (Stream responseStream = wbResponse.GetResponseStream())
               {
                   using (StreamReader sread = new StreamReader(responseStream))
                   {
                       result = sread.ReadToEnd();
                   }
               }
           }
           catch (Exception ex)
           { }
         
           return result;
       }
HttpPost

 

#region 文件上传

        /// <summary>
        /// 文件上传的方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="attachment"></param>
        /// <param name="filePath"></param>
        /// <param name="keyName"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public static string FileUpload(string url, string attachment, string filePath,string fileName, string keyName = "X-Gaia-Api-Key", string keyValue = "b54206e3-3b37-46aa-aa29-04e7f6efcb77")
        {
            string result = "";
            try
            {
                Encoding currentEncode = Encoding.GetEncoding("utf-8");
                string boundary = Guid.NewGuid().ToString();
                string beginBoundary = "--" + boundary;
                string endBoundary = "--" + boundary + "--";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = "POST";
                //request.KeepAlive = true;
                request.Headers.Add(keyName, keyValue);
                StringBuilder sbBody = new StringBuilder();
                sbBody.AppendLine(beginBoundary);
                sbBody.AppendLine("Content-Disposition: form-data; name=\"attachment\"");
                sbBody.AppendLine();
                sbBody.AppendLine(attachment);



                sbBody.AppendLine(beginBoundary);
                sbBody.AppendLine(string.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"", fileName));
                sbBody.AppendLine("Content-Type: application/octet-stream");
                sbBody.AppendLine();

                byte[] bufferContent = currentEncode.GetBytes(sbBody.ToString());
                byte[] bufferFile = GetFileByte(filePath);
                byte[] bufferEndBoundary = currentEncode.GetBytes("\r\n" + endBoundary);

                byte[] bufferBody = new byte[bufferContent.Length + bufferFile.Length + bufferEndBoundary.Length];
                int startIndex = 0;
                bufferContent.CopyTo(bufferBody, startIndex);
                startIndex += bufferContent.Length;
                bufferFile.CopyTo(bufferBody, startIndex);
                startIndex += bufferFile.Length;
                bufferEndBoundary.CopyTo(bufferBody, startIndex);

                request.ContentLength = bufferBody.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bufferBody, 0, bufferBody.Length);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = new StreamReader(receiveStream, currentEncode);

                result = readStream.ReadToEnd();
                response.Close();
                readStream.Close();
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog($"上传文件异常信息:{attachment}", $"ex:{ex.Message},trace:{ex.StackTrace},source:{ex.Source}");
            }
           
            return result;
        }

        /// <summary>
        /// 获取文件字节流
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static byte[] GetFileByte(string filePath)
        {
            byte[] bufferFileInfo = null;
            using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                bufferFileInfo = new byte[stream.Length];
                stream.Read(bufferFileInfo, 0, bufferFileInfo.Length);
            }

            return bufferFileInfo;

        }
        #endregion
HttpPostFile

 

  public static async Task<string> FileUpload(string url, string attachment, string filePath, string fileName, string keyName = "X-Gaia-Api-Key", string keyValue = "b54206e3-3b37-46aa-aa29-04e7f6efcb77")
        {
            string result = "";
            try
            {
                using (var httpClient = new HttpClient() { BaseAddress = new Uri(url) })
                {
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    TimeSpan ts = new TimeSpan(0, 20, 0);
                    httpClient.Timeout = ts;
                    Console.WriteLine(attachment);
                    using (Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        MultipartFormDataContent formData = new MultipartFormDataContent();
                        formData.Add(new StringContent(attachment), "attachment");// 使用""来转义

                        formData.Add(new StreamContent(fileStream, (Int32)fileStream.Length), "file", fileName);
                        HttpResponseMessage response = await httpClient.PostAsync(url, formData);
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            result = await response.Content.ReadAsStringAsync();
                            Console.WriteLine(result);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(result);
            }
            return result;
        }
HttpFileUpload

 

 

public async static Task<string> HttpPostFormData(string url, Dictionary<string, string> headerDic , Dictionary<string, string> postParam)
        {
            string result = "";
            HttpClient client = new HttpClient();
            if (headerDic != null && headerDic.Count > 0)
            {
                foreach (var item in headerDic)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            MultipartFormDataContent formContent = new MultipartFormDataContent();
            foreach(var item in postParam)
            {
                formContent.Add(new StringContent(item.Value),item.Key);
            }
           var response=await client.PostAsync(url, formContent);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                result = response.Content.ReadAsStringAsync().Result;
            }
            return result ;
        }
HttpPost formdata

 

  

  

posted @ 2016-09-27 14:58  kaikaichao  阅读(20740)  评论(0编辑  收藏  举报