• C# .Net WebClient http及https请求


    C# .Net WebClient http及https请求及上传文件

    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Web;
    
    namespace Tools
    {
        public class RestfullRequest
        {
            public static string Request(string url, string method, string contentType, string data, NameValueCollection header = null, NetworkCredential credential = null,
                string proxyAddress = null, Encoding responseEncoding = null)
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                
                if (url.StartsWith("https://"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidate);//验证服务器证书回调自动验证
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                }
                request.Method = method;
                if (!string.IsNullOrEmpty(contentType))
                    request.ContentType = contentType;
                if (header != null)
                    request.Headers.Add(header);
                if (credential != null)
                    request.Credentials = credential;
    
                if (!string.IsNullOrEmpty(proxyAddress))
                {
                    IWebProxy proxy = new WebProxy(proxyAddress);
                    proxy.Credentials = new NetworkCredential();
                    request.Proxy = proxy;
                }
    
                if (!string.IsNullOrEmpty(data))
                {
                    using (var swt = new StreamWriter(request.GetRequestStream()))
                    {
                        swt.Write(data);
                    }
                }
    
                string result = string.Empty;
                using (WebResponse response = request.GetResponse())
                {
                    if (response.ContentType.IndexOf("octet-stream") > -1)
                    {
                        string dispositionStr = response.Headers["Content-Disposition"];
                        int fileNameI = dispositionStr.IndexOf("filename=");
                        string fileName = dispositionStr.Substring(fileNameI + 9, dispositionStr.Length - (fileNameI + 9));
                        fileName = HttpUtility.UrlDecode(fileName, Encoding.UTF8);
                        string downpath = AppDomain.CurrentDomain.BaseDirectory + "Download";
                        if (!Directory.Exists(downpath)) {
                            Directory.CreateDirectory(downpath);
                        }
                        string downFile= downpath + "\\" + fileName;
    
                        if (File.Exists(downFile))
                        {
                            File.Delete(downFile);
                        }
                        Stream inStream = response.GetResponseStream();
                        using (Stream outStream = File.OpenWrite(downFile)) {
                            byte[] buffer = new byte[8192];
                            int size = 0;
                            while ((size = inStream.Read(buffer, 0, 8192)) > 0)
                            {
                                outStream.Write(buffer, 0, size);
                            }
                        }
                        result = downFile;
                    }
                    else {
                        Stream stream = response.GetResponseStream();
                        if (responseEncoding == null) responseEncoding = Encoding.UTF8;
                        StreamReader myStreamReader = new StreamReader(stream, responseEncoding);
                        result = myStreamReader.ReadToEnd();
                        myStreamReader.Close();
                        stream.Close();
                        //byte[] buf = new byte[1024];
                        //while (true)
                        //{
                        //    int len = stream.Read(buf, 0, buf.Length);
                        //    if (len <= 0)//len <= 0 跳出循环
                        //        break;
                        //    if (responseEncoding == null) responseEncoding = Encoding.UTF8;
                        //     result += responseEncoding.GetString(buf, 0, len);//指定编码格式
                        //}
                    }
                    //using (var sr = new StreamReader(response.GetResponseStream()))
                    //{
                    //    result = sr.ReadToEnd();
                    //}
                }
                
                return result;
            }
    
            /// <summary>
            /// HttpWebRequest发送文件
            /// </summary>
            /// <param name="url">url</param>
            /// <param name="fileName">文件路径</param>
            /// <param name="fileParaName">文件参数名</param>
            /// <param name="contentType">contentType</param>
            /// <param name="nameValueCollection">其余要附带的参数键值对</param>
            public static string RequestUploadFile(string url, byte[] buffer, string fileParaName, string fileName, NameValueCollection nameValueCollection, string contentType="application/octet-stream")
            {
                string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = "POST";
                request.KeepAlive = true;
                request.Credentials = CredentialCache.DefaultCredentials;
                Stream requestStream = request.GetRequestStream();
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                if (nameValueCollection != null) {
                    foreach (string key in nameValueCollection.Keys)
                    {
                        requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                        string formitem = string.Format(formdataTemplate, key, nameValueCollection[key]);
                        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                        requestStream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }
                requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                string header = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", fileParaName, fileName, contentType);
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                requestStream.Write(headerbytes, 0, headerbytes.Length);
                //FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                //byte[] buffer = new byte[4096];
                //int bytesRead = 0;
                //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                //{
                //    requestStream.Write(buffer, 0, bytesRead);
                //}
                //fileStream.Close();
                requestStream.Write(buffer, 0, buffer.Length);
                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                requestStream.Write(trailer, 0, trailer.Length);
                requestStream.Close();
                WebResponse webResponse = null;
                try
                {
                    webResponse = request.GetResponse();
                    Stream responseStream = webResponse.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream);
                    string result = streamReader.ReadToEnd();
                    return result;
                }
                catch (Exception ex)
                {
                    if (webResponse != null)
                    {
                        webResponse.Close();
                        webResponse = null;
                    }
                }
                finally
                {
                    request = null;
                }
                return "";
            }
    
            private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
            {
                //为了通过证书验证,总是返回true
                return true;
            }
    
            public static bool IsFileInUse(string fileName)
            {
                bool inUse = true;
    
                FileStream fs = null;
                try
                {
    
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
    
                    FileShare.None);
    
                    inUse = false;
                }
                catch
                {
    
                }
                finally
                {
                    if (fs != null)
    
                        fs.Close();
                }
                return inUse;//true表示正在使用,false没有使用
            }
        }
    }
  • 相关阅读:
    SpringMVC【二、项目搭建】
    SpringMVC【一、概述】
    VUE【四、组件】
    VUE【三、指令】
    VUE【二、选项和生命周期】
    VUE【一、概述】
    BootStrap【四、插件】
    BootStrap【三、组件】
    BootStrap【二、样式】
    C#+ArcEngine创建企业数据库、连接及相关
  • 原文地址:https://www.cnblogs.com/xiaoruilin/p/15668597.html
Copyright © 2020-2023  润新知