【C#】.net 發送get/post請求

基礎學習html

/// <summary>
/// Http (GET/POST)
/// </summary>
/// <param name="url">請求URL</param>
/// <param name="parameters">請求參數</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
    {
        //建立請求
        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>
        /// 解決使用上面方法向同一個地址發送請求時會發生:基礎鏈接已經關閉: 服務器關閉了本應保持活動狀態的鏈接的問題
        /// </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>
/// 組裝普通文本請求參數。
/// </summary>
/// <param name="parameters">Key-Value形式請求參數字典</param>
/// <returns>URL編碼後的請求數據</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;
        // 忽略參數名或參數值爲空的參數
        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");
使用示例

 

 

進階學習api

1、讀取本地圖片文件,進行上傳服務器

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");

            // 組裝文本請求參數
            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);
            }

            // 組裝文件請求參數
            #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);
使用示例

2、讀取網絡上的圖片文件,進行上傳網絡

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");

            // 組裝文本請求參數
            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);
            }

            // 組裝文件請求參數
            #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);
使用示例
相關文章
相關標籤/搜索