<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      【C#】.net 發(fā)送get/post請求

      基礎學習

      /// <summary>
      /// Http (GET/POST)
      /// </summary>
      /// <param name="url">請求URL</param>
      /// <param name="parameters">請求參數(shù)</param>
      /// <param name="method">請求方法</param>
      /// <returns>響應內容</returns>
      static string sendPost(string url, IDictionary<string, string> parameters, string method)
      {
          if (method.ToLower() == "post")
          {
              HttpWebRequest req = null;
              HttpWebResponse rsp = null;
              System.IO.Stream reqStream = null;
              try
              {
                  req = (HttpWebRequest)WebRequest.Create(url);
                  req.Method = method;
                  req.KeepAlive = false;
                  req.ProtocolVersion = HttpVersion.Version10;
                  req.Timeout = 5000;
                  req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                  byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                  reqStream = req.GetRequestStream();
                  reqStream.Write(postData, 0, postData.Length);
                  rsp = (HttpWebResponse)req.GetResponse();
                  Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                  return GetResponseAsString(rsp, encoding);
              }
              catch (Exception ex)
              {
                  return ex.Message;
              }
              finally
              {
                  if (reqStream != null) reqStream.Close();
                  if (rsp != null) rsp.Close();
              }
          }
          else
          {
              //創(chuàng)建請求
              HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
      
              //GET請求
              request.Method = "GET";
              request.ReadWriteTimeout = 5000;
              request.ContentType = "text/html;charset=UTF-8";
              HttpWebResponse response = (HttpWebResponse)request.GetResponse();
              Stream myResponseStream = response.GetResponseStream();
              StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
      
              //返回內容
              string retString = myStreamReader.ReadToEnd();
              return retString;
          }
      }
      方法代碼
      public HttpWebRequest GetWebRequest(string url, string method)
              {
                  HttpWebRequest request = null;
                  if (url.Contains("https"))
                  {
                      ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult);
                      request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                  }
                  else
                  {
                      request = (HttpWebRequest)WebRequest.Create(url);
                  }
                  request.ServicePoint.Expect100Continue = false;
                  request.Method = method;
                  request.KeepAlive = true;
                  request.UserAgent = "stgp";
                  return request;
              }
      
              /// <summary>
              /// 解決使用上面方法向同一個地址發(fā)送請求時會發(fā)生:基礎連接已經(jīng)關閉: 服務器關閉了本應保持活動狀態(tài)的連接的問題
              /// </summary>
              /// <param name="url"></param>
              /// <param name="method"></param>
              /// <returns></returns>
              public HttpWebRequest GetWebRequestDotnetReference(string url, string method)
              {
                  HttpWebRequest request = null;
                  if (url.Contains("https"))
                  {
                      ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult);
                      request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                  }
                  else
                  {
                      request = (HttpWebRequest)WebRequest.Create(url);
                  }
      
                  request.Method = method;
                  request.KeepAlive = false;//fase
                  request.ProtocolVersion = HttpVersion.Version11;//Version11
                  request.UserAgent = "stgp";
                  return request;
              }
      方法代碼
      /// <summary>
      /// 組裝普通文本請求參數(shù)。
      /// </summary>
      /// <param name="parameters">Key-Value形式請求參數(shù)字典</param>
      /// <returns>URL編碼后的請求數(shù)據(jù)</returns>
      static string BuildQuery(IDictionary<string, string> parameters, string encode)
      {
          StringBuilder postData = new StringBuilder();
          bool hasParam = false;
          IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
          while (dem.MoveNext())
          {
              string name = dem.Current.Key;
              string value = dem.Current.Value;
              // 忽略參數(shù)名或參數(shù)值為空的參數(shù)
              if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
              {
                  if (hasParam)
                  {
                      postData.Append("&");
                  }
                  postData.Append(name);
                  postData.Append("=");
                  if (encode == "gb2312")
                  {
                      postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                  }
                  else if (encode == "utf8")
                  {
                      postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                  }
                  else
                  {
                      postData.Append(value);
                  }
                  hasParam = true;
              }
          }
          return postData.ToString();
      }
      方法代碼
      /// <summary>
      /// 把響應流轉換為文本。
      /// </summary>
      /// <param name="rsp">響應流對象</param>
      /// <param name="encoding">編碼方式</param>
      /// <returns>響應文本</returns>
      static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
      {
          System.IO.Stream stream = null;
          StreamReader reader = null;
          try
          {
              // 以字符流的方式讀取HTTP響應
              stream = rsp.GetResponseStream();
              reader = new StreamReader(stream, encoding);
              return reader.ReadToEnd();
          }
          finally
          {
              // 釋放資源
              if (reader != null) reader.Close();
              if (stream != null) stream.Close();
              if (rsp != null) rsp.Close();
          }
      }
      方法代碼

       

      string url = "http://www.example.com/api/exampleHandler.ashx";
      var parameters = new Dictionary<string, string>();
      parameters.Add("param1", "1"); 
      parameters.Add("param2", "2"); 
      
      string result = sendPost(url, parameters, "get");
      使用示例

       

       

      進階學習

      一、讀取本地圖片文件,進行上傳

      public string DoPostWithFile(string url, IDictionary<string, string> textParams, List<string> filePathList, string charset = "utf-8")
              {
                  string boundary = "-------" + DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
      
                  HttpWebRequest req = GetWebRequestDotnetReference(url, "POST");
                  req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary;
      
                  System.IO.Stream reqStream = req.GetRequestStream();
                  byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
                  byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n");
      
                  // 組裝文本請求參數(shù)
                  string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
                  IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
                  while (textEnum.MoveNext())
                  {
                      string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
                      byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
                      reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                      reqStream.Write(itemBytes, 0, itemBytes.Length);
                  }
      
                  // 組裝文件請求參數(shù)
                  #region 將文件轉成二進制
                  string fileName = string.Empty;
                  byte[] fileContentByte = new byte[1024];
      
                  string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\n\r\n";
                  foreach (string filePath in filePathList)
                  {
                      fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
      
                      FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                      fileContentByte = new byte[fs.Length];
                      fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length));
                      fs.Close();
      
                      string fileEntry = string.Format(fileTemplate, "images[]", fileName);
                      byte[] itemBytesF = Encoding.GetEncoding(charset).GetBytes(fileEntry);
                      reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                      reqStream.Write(itemBytesF, 0, itemBytesF.Length);
                      reqStream.Write(fileContentByte, 0, fileContentByte.Length);
                  }
                  #endregion
      
                  reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                  reqStream.Close();
      
                  HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
                  Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                  return GetResponseAsString(rsp, encoding);
              }
      方法代碼
      string url = "http://www.example.com/api/exampleHandler.ashx";
      var param = new Dictionary<string, string>();
       param.Add("param1", "1");
      List<string> filePathList = new List<string>();
      filePathList.Add(@"C:\Users\pic1.png");
      
      string result = DoPostWithFile(url, param, filePathList);
      使用示例

      二、讀取網(wǎng)絡上的圖片文件,進行上傳

      public string DoPostWithNetFile(string url, IDictionary<string, string> textParams, List<string> filePathList, string charset = "utf-8")
              {
                  string boundary = "-------" + DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
      
                  //HttpWebRequest req = GetWebRequest(url, "POST");
                  HttpWebRequest req = GetWebRequestDotnetReference(url, "POST");
                  req.ContentType = "multipart/form-data;charset=" + charset + ";boundary=" + boundary;
      
                  System.IO.Stream reqStream = req.GetRequestStream();
                  byte[] itemBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "\r\n");
                  byte[] endBoundaryBytes = Encoding.GetEncoding(charset).GetBytes("\r\n--" + boundary + "--\r\n");
      
                  // 組裝文本請求參數(shù)
                  string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
                  IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
                  while (textEnum.MoveNext())
                  {
                      string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
                      byte[] itemBytes = Encoding.GetEncoding(charset).GetBytes(textEntry);
                      reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                      reqStream.Write(itemBytes, 0, itemBytes.Length);
                  }
      
                  // 組裝文件請求參數(shù)
                  #region 將文件轉成二進制
                  string fileName = string.Empty;
                  byte[] fileContentByte = new byte[1024];
      
                  string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\n\r\n";
                  foreach (string filePath in filePathList)
                  {
                      fileName = filePath.Substring(filePath.LastIndexOf(@"/") + 1);
      
      
      
                      HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(filePath);
                      imgRequest.Method = "GET";
                      using (HttpWebResponse imgResponse = imgRequest.GetResponse() as HttpWebResponse)
                      {
                          if (imgResponse.StatusCode == HttpStatusCode.OK)
                          {
                              Stream rs = imgResponse.GetResponseStream();
      
                              MemoryStream ms = new MemoryStream();
                              const int bufferLen = 4096;
                              byte[] buffer = new byte[bufferLen];
                              int count = 0;
                              while ((count = rs.Read(buffer, 0, bufferLen)) > 0)
                              {
                                  ms.Write(buffer, 0, count);
                              }
      
      
                              ms.Seek(0, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先轉為MemoryStream
                              fileContentByte = new byte[buffsize];
      
                              ms.Read(fileContentByte, 0, buffsize);
                              ms.Flush(); ms.Close();
                              rs.Flush(); rs.Close();
                          }
                      }
      
                      string fileEntry = string.Format(fileTemplate, "images[]", fileName);
                      byte[] itemBytesF = Encoding.GetEncoding(charset).GetBytes(fileEntry);
                      reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                      reqStream.Write(itemBytesF, 0, itemBytesF.Length);
                      reqStream.Write(fileContentByte, 0, fileContentByte.Length);
                  }
                  #endregion
      
                  reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                  reqStream.Close();
      
                  HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
                  Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                  return GetResponseAsString(rsp, encoding);
              }
      方法代碼
      string url = "http://www.example.com/api/exampleHandler.ashx";
      var param = new Dictionary<string, string>();
      param.Add("param1", "1");
      List<string> filePathList = new List<string>();
      filePathList.Add(@"http://www.example.com/img/pic1.png");
      
      string result = DoPostWithNetFile(url, param, filePathList);
      使用示例

       

      posted @ 2017-01-12 17:26  Doc.stu  閱讀(6696)  評論(0)    收藏  舉報
      主站蜘蛛池模板: 亚洲成人av一区二区| 叙永县| 欧美日韩一线| 日韩av不卡一区二区在线| 丁香婷婷无码不卡在线| 日韩中文字幕有码av| 国产无遮挡免费视频免费| 樱花草视频www日本韩国| 黑人巨大精品欧美| 国产福利永久在线视频无毒不卡| 日韩精品一区二区三免费| 国产老熟女国语免费视频| 91中文字幕在线一区| 日本a在线播放| 免费看成人毛片无码视频| 绥中县| 久久无码人妻精品一区二区三区 | 国产suv精品一区二区883| 亚洲综合av男人的天堂| 午夜成年男人免费网站| 露脸叫床粗话东北少妇| 色欲综合久久中文字幕网| 亚洲国产综合一区二区精品| 夜夜添狠狠添高潮出水| 女人喷水高潮时的视频网站| 国产乱码日产乱码精品精| 国产一区二区三区不卡在线看| 国产睡熟迷奷系列网站| 亚洲中文字字幕精品乱码| 免费看的一级毛片| 国产午夜A理论毛片| 国产精品黄大片在线播放| 欧美成人性色一区欧美成人性色区| 在线a级毛片无码免费真人| 国产啪视频免费观看视频| 成人无码午夜在线观看| 国内精品自线在拍| 国产一区二区三区四区五区加勒比 | 欧美一区二区三区性视频| 国产午夜福利一区二区三区| 少妇又紧又色又爽又刺激视频|