C# 傳送Http請求,傳檔案和其他引數
阿新 • • 發佈:2021-12-23
/// <summary> /// httpWebRequest post by dic /// </summary> /// <param name="url">url</param> /// <param name="APIID">appid</param> /// <param name="dicParams">引數</param> /// <param name="filePath">檔案路徑</param> /// <param name="fileParamName">檔案對應的引數名</param> /// <returns></returns> public static string httpWebRequestPost(string url, string APIID, Dictionary<string, string> dicParams, string filePath, string fileParamName) { string boundary = "ceshi"//getRandomString(32, true, true, false, false, ""); string Enter = "\r\n"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "multipart/form-data;boundary=" + boundary; Stream requestStream = request.GetRequestStream(); int dicParamsIndex = 0; #region 寫入請求流 foreach (var item in dicParams) { #region 定義請求體中的內容 並轉成二進位制 string s = dicParamsIndex == 0 ? "" : Enter; s += "--" + boundary + Enter + "Content-Disposition: form-data; name=\"" + item.Key + "\"" + Enter + Enter + item.Value; var bytes = Encoding.UTF8.GetBytes(s);//encrypt所有字串二進位制 #endregion #region 將各個二進位制 寫入請求流 requestStream.Write(bytes, 0, bytes.Length); #endregion dicParamsIndex++; } #endregion #region 將檔案轉成二進位制 if (fileParamName != "" && filePath != "") { string fileName = System.IO.Path.GetFileName(filePath); byte[] fileBytes = File.ReadAllBytes(filePath); string fileStr = Enter + "--" + boundary + Enter + "Content-Type:application/octet-stream" + Enter + "Content-Disposition: form-data; name=\"file\"; " + "filename=\"" + fileName + "\"" + Enter + Enter; var fileStrByte = Encoding.UTF8.GetBytes(fileStr);//encrypt所有字串二進位制 requestStream.Write(fileStrByte, 0, fileStrByte.Length); requestStream.Write(fileBytes, 0, fileBytes.Length); } #endregion #region 結束標籤 string endStr = Enter + "--" + boundary + "--"; var endBytes = Encoding.UTF8.GetBytes(endStr); requestStream.Write(endBytes, 0, endBytes.Length); #endregion #region 傳送請求 HttpWebResponse response = (HttpWebResponse)request.GetResponse();//傳送 Stream responseStream = response.GetResponseStream();//獲取返回值 StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); string responseString = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); #endregion return responseString; }