C# HTTP请求 get post
C# HTTP请求 get post
public class HttpRequestHelper { public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } /// <summary> /// 向指定URL发送GET方法的请求 /// </summary> /// <param name="url">发送请求的URL</param> /// <param name="param">请求参数,请求参数应该是 name1=value1&name2=value2 的形式。</param> /// <returns>所代表远程资源的响应结果</returns> public static string SendGet(string url, string param) { string result = String.Empty; StreamReader reader = null; try { string urlNameString = url + "?" + param; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlNameString); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; request.Accept = "*/*"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; #region 没有证书 //ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; request = (HttpWebRequest)HttpWebRequest.Create(url); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //设置协议类型前设置协议版本req.ProtocolVersion = HttpVersion.Version11; //这里设置了协议类型。 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 1000; ServicePointManager.Expect100Continue = false; #endregion HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; } Stream responseStream = response.GetResponseStream(); reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); result = reader.ReadToEnd(); reader.Close(); responseStream.Close(); response.Close(); reader = null; responseStream = null; response = null; } catch (Exception ex) { Console.WriteLine("发送GET请求出现异常:" + ex.Message); } finally { if (reader != null) { reader.Close(); } } return result; } /// <summary> /// 向指定URL发送GET方法的请求 /// </summary> /// <param name="url">发送请求的URL</param> /// <param name="param">请求参数,请求参数应该是 name1=value1&name2=value2 的形式。</param> /// <param name="encoding">设置响应信息的编码格式,如utf-8</param> /// <returns>所代表远程资源的响应结果</returns> public static string SendGet(string url, string param, string encoding) { string result = String.Empty; StreamReader reader = null; try { string urlNameString = url + "?" + param; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlNameString); request.Method = "GET"; request.ContentType = "text/html;charset=" + encoding; request.Accept = "*/*"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); reader = new StreamReader(responseStream, Encoding.GetEncoding(encoding)); result = reader.ReadToEnd(); reader.Close(); responseStream.Close(); response.Close(); reader = null; responseStream = null; response = null; } catch (Exception ex) { Console.WriteLine("发送GET请求出现异常:" + ex.Message); } finally { if (reader != null) { reader.Close(); } } return result; } /// <summary> /// 向指定 URL 发送POST方法的请求 /// </summary> /// <param name="url">发送请求的 URL</param> /// <param name="jsonData">请求参数,请求参数应该是Json格式字符串的形式。</param> /// <returns>所代表远程资源的响应结果</returns> public static string SendPost(string url, string jsonData) { string result = String.Empty; try { CookieContainer cookie = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Headers.Add("x-requested-with", "XMLHttpRequest"); request.ServicePoint.Expect100Continue = false; request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "*/*"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; request.ContentLength = Encoding.UTF8.GetByteCount(jsonData); request.CookieContainer = cookie; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write(jsonData); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Cookies = cookie.GetCookies(response.ResponseUri); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { result = reader.ReadToEnd(); reader.Close(); } responseStream.Close(); } response.Close(); response = null; request = null; } catch (Exception ex) { Console.WriteLine("发送GET请求出现异常:" + ex.Message); } return result; } /// <summary> /// 向指定 URL 发送POST方法的请求 /// </summary> /// <param name="url">发送请求的 URL</param> /// <param name="jsonData">请求参数,请求参数应该是Json格式字符串的形式。</param> /// <param name="encoding">设置响应信息的编码格式,如utf-8</param> /// <returns>所代表远程资源的响应结果</returns> public static string SendPost(string url, string jsonData, string encoding) { string result = String.Empty; try { CookieContainer cookie = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Headers.Add("x-requested-with", "XMLHttpRequest"); request.ServicePoint.Expect100Continue = false; request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "*/*"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; request.ContentLength = Encoding.UTF8.GetByteCount(jsonData); request.CookieContainer = cookie; using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.GetEncoding(encoding))) { writer.Write(jsonData); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Cookies = cookie.GetCookies(response.ResponseUri); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding(encoding))) { result = reader.ReadToEnd(); reader.Close(); } responseStream.Close(); } response.Close(); response = null; request = null; } catch (Exception ex) { Console.WriteLine("发送GET请求出现异常:" + ex.Message); } return result; } /// <summary> /// 上传媒体文件 /// </summary> /// <param name="url">上传媒体文件的微信公众平台接口地址</param> /// <param name="file">要上传的媒体文件对象</param> /// <returns>返回上传的响应结果,详情参看微信公众平台开发者接口文档</returns> public static string UploadPost(string url, string file) { string result = String.Empty; try { WebClient client = new WebClient(); client.Credentials = CredentialCache.DefaultCredentials; byte[] responseArray = client.UploadFile(url, "POST", file); result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length); Console.WriteLine("上传result:" + result); } catch (Exception ex) { result = "Error:" + ex.Message; Console.WriteLine("发送GET请求出现异常:" + ex.Message); } finally { Console.WriteLine("上传MediaId:" + result); } return result; } public static bool DownloadFile(string url, string param, string outFileName) { bool result = false; FileStream fs = null; try { string urlNameString = url + "?" + param; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlNameString); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; request.Accept = "*/*"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); fs = new FileStream(outFileName, FileMode.Create); int bufferSize = 2048; byte[] data = new byte[bufferSize]; int length = 0; while ((length = responseStream.Read(data, 0, bufferSize)) > 0) { fs.Write(data, 0, length); } fs.Close(); responseStream.Close(); response.Close(); fs = null; responseStream = null; response = null; result = true; } catch (Exception ex) { Console.WriteLine("下载媒体文件时出现异常:" + ex.Message); } finally { if (fs != null) { fs.Close(); } } return result; }
https://blog.csdn.net/u014361280/article/details/132595757
1、HttpWebRequest 常用属性
AllowAutoRedirect:获取或设置一个值,该值指示请求是否应跟随重定向响应。
CookieContainer:获取或设置与此请求关联的cookie。
Credentials:获取或设置请求的身份验证信息。
KeepAlive:获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接。
MaximumAutomaticRedirections:获取或设置请求将跟随的重定向的最大数目。
Proxy:获取或设置请求的代理信息。
SendChunked:获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。
Timeout:获取或设置请求的超时值。
UserAgent:获取或设置 User-agent HTTP 标头的值
ContentType:Http内容类型
Headers:指定组成 HTTP 标头的名称/值对的集合。
2、HttpWebRequest 中的 ContentType
普通文本: “text/plain”
JSON字符串: “application/json”
数据流类型(文件流): “application/octet-stream”
表单数据(键值对): “application/x-www-form-urlencoded”
多分部数据: “multipart/form-data”
/// <summary> /// Get请求 /// </summary> /// <param name="url"></param> /// <param name="dic"></param> /// <returns></returns> public static string GetMethod(string url, Dictionary<string, string> dic) { try { StringBuilder builder = new StringBuilder(); builder.Append(url); if (dic != null && dic.Count > 0) { builder.Append("?"); int i = 0; foreach (var item in dic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; } } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(builder.ToString()); request.Method = "GET"; //request.ContentType = "text/html;charset=UTF-8"; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取response的流 Stream myResponseStream = response.GetResponseStream(); //使用streamReader读取流数据 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } catch (WebException e) { string errInfo = string.Empty; logger.ErrorFormat($"{url},访问异常,{e.Message}"); return null; } } /// <summary> /// Get异步请求 /// </summary> /// <param name="url"></param> /// <param name="dic"></param> /// <returns></returns> public static async Task<string> GetMethodAsync(string url, Dictionary<string, string> dic) { try { StringBuilder builder = new StringBuilder(); builder.Append(url); if (dic != null && dic.Count > 0) { builder.Append("?"); int i = 0; foreach (var item in dic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; } } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(builder.ToString()); request.Method = "GET"; //request.ContentType = "text/html;charset=UTF-8"; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); //获取response的流 Stream myResponseStream = response.GetResponseStream(); //使用streamReader读取流数据 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } catch (WebException e) { string errInfo = string.Empty; logger.ErrorFormat($"{url},访问异常,{e.Message}"); return null; } } /// <summary> /// Post请求 /// </summary> /// <param name="url"></param> /// <param name="postData">json格式的请求报文,例如:{"key1":"value1","key2":"value2"}</param> /// <param name="timeOut"></param> /// <returns></returns> public static string PostMethod(string url, string postData, int timeOut = 180000) { //url = webApiUrl + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; request.Timeout = timeOut; byte[] payload = Encoding.UTF8.GetBytes(postData); using (Stream myRequestStream = request.GetRequestStream()) { myRequestStream.Write(payload, 0, payload.Length); myRequestStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); //获取响应内容 string retString = string.Empty; using (StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8)) { retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); } return retString; } public static async Task<string> PostMethodAsync(string url, string postDataStr, int timeOut = 180000) { //url = webApiUrl + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; request.Timeout = timeOut; Stream myRequestStream = await request.GetRequestStreamAsync(); byte[] payload = Encoding.UTF8.GetBytes(postDataStr); await myRequestStream.WriteAsync(payload, 0, payload.Length); myRequestStream.Close(); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } public static async Task<string> PostRequestWithTokenAsync(string url, string postData,string token, int timeOut = 180000) { try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.ReadWriteTimeout = timeOut; request.Timeout = timeOut; request.Method = "POST"; request.ContentType = "application/json"; // 根据需要设定 request.Headers.Add("token", token); // 根据需要设定 //request.Headers.Add("xxxx-authorization", m_Authorization); // 根据需要设定 //流式发起请求 using (Stream requestStream = await request.GetRequestStreamAsync()) { byte[] dataBytes = Encoding.UTF8.GetBytes(postData); await requestStream.WriteAsync(dataBytes, 0, dataBytes.Length); } //流式获取数据响应 using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) { StringBuilder sb = new StringBuilder(); char[] buffer = new char[1024]; int bytesRead; // 循环获取流式数据 while ((bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0) { sb.Append(buffer, 0, bytesRead); //Console.WriteLine(buffer); buffer = new char[1024]; } return sb.ToString(); } //string responseContent = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd(); } catch (Exception ex) { return null; } } /// <summary> /// 上传文件请求 /// </summary> /// <param name="url">Url</param> /// <param name="filePath">文件路径</param> /// <param name="formDatas">表单数据(字典格式)</param> /// <param name="callback">上传回调</param> public static void UploadRequest(string url, string filePath, Dictionary<string, string> formDatas, Action<string> callback) { // 时间戳,用做boundary string timeStamp = DateTime.Now.Ticks.ToString("x"); //根据uri创建HttpWebRequest对象 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(url)); httpReq.Method = "POST"; httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存 httpReq.Timeout = 300000; //设置获得响应的超时时间(300秒) httpReq.ContentType = "multipart/form-data; boundary=" + timeStamp; //读取file文件 FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader binaryReader = new BinaryReader(fileStream); //表单信息 string boundary = "--" + timeStamp; string form = ""; string formFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n"; string formEnd = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type:application/octet-stream\r\n\r\n"; foreach (var pair in formDatas) { form += string.Format(formFormat, pair.Key, pair.Value); } form += string.Format(formEnd, "file", Path.GetFileName(filePath)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(form); //结束边界 byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + timeStamp + "--\r\n"); long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length; httpReq.ContentLength = length; //请求内容长度 try { //每次上传4k int bufferLength = 4096; byte[] buffer = new byte[bufferLength]; //已上传的字节数 long offset = 0; int size = binaryReader.Read(buffer, 0, bufferLength); Stream postStream = httpReq.GetRequestStream(); //发送请求头部消息 postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); while (size > 0) { postStream.Write(buffer, 0, size); offset += size; size = binaryReader.Read(buffer, 0, bufferLength); } //添加尾部边界 postStream.Write(boundaryBytes, 0, boundaryBytes.Length); postStream.Close(); //获取服务器端的响应 using (HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse()) { Stream receiveStream = response.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); string returnValue = readStream.ReadToEnd(); //Debug.Log("upload result:" + returnValue); callback?.Invoke(returnValue); response.Close(); readStream.Close(); } } catch (Exception ex) { //Debug.Log("文件传输异常: " + ex.Message); } finally { fileStream.Close(); binaryReader.Close(); } }