首页 > 编程语言 >C# HttpWebRequest 各种请求方式汇总

C# HttpWebRequest 各种请求方式汇总

时间:2024-07-02 11:52:33浏览次数:24  
标签:string C# 汇总 req request Length HttpWebRequest new

GET

//直接返回字符串
public static string Gets(string url, JObject headers)
{
    string result = "";
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "Get";
    if (headers != null)
    {
        IEnumerable<JProperty> properties = headers.Properties();
        foreach (JProperty item in properties)
        {
            req.Headers.Add(item.Name, item.Value.ToString());
        }
    }
    try
    {
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        Stream stream = resp.GetResponseStream();
        //获取内容
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }
    }
    catch (Exception ex)
    {
        result = ex.Message;
    }
    return result;
}

// 直接读取文件流
public static string HttpGet(string url)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "Get";
    try
    {
        using (WebResponse wr = req.GetResponse())
        {
            HttpWebResponse response = wr as HttpWebResponse;
            Stream stream = response.GetResponseStream();
            //读取到内存
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = stream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            string content = Convert.ToBase64String(ms.ToArray());
            return content;
        }
    }
    catch (Exception ex)
    {
        return null;
    }
}

POST

application/json

public static string PostWebRequest(string postUrl, string paramData, int? timeOut)
{
    string responseContent = string.Empty;
    try
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
        webReq.Method = "POST";
        //这里的格式根据自己需求替换
        webReq.ContentType = "application/json";
        webReq.ContentLength = byteArray.Length;
        if(timeOut != null) webReq.Timeout = (int)timeOut;
        using (Stream reqStream = webReq.GetRequestStream())
        {
            reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
            //reqStream.Close();
        }
        using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
        {
            //在这里对接收到的页面内容进行处理
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                responseContent = sr.ReadToEnd().ToString();
            }
        }
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
    return responseContent;
}

application/x-www-form-urlencoded

public static string PostUrlFormUrlencoded(string url, string postData)
{
    string result = "";
    try
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

        req.Method = "POST";

        req.ContentType = "application/x-www-form-urlencoded";

        //req.Timeout = 8000;//请求超时时间

        byte[] data = Encoding.UTF8.GetBytes(postData);

        req.ContentLength = data.Length;

        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(data, 0, data.Length);

            reqStream.Close();
        }

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        Stream stream = resp.GetResponseStream();

        //获取响应内容
        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("发送请求出错:" + e.Message);
    }

    return result;
}

multipart/form-data

public static string HttpPost(string url, NameValueCollection kVDatas = null, JObject headers = null,
    string method = WebRequestMethods.Http.Post, int timeOut = -1)
{
    try
    {
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
        byte[] endbytes = 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.Timeout = timeOut;
        if (headers != null)
        {
            IEnumerable<JProperty> properties = headers.Properties();
            foreach (JProperty item in properties)
            {
                request.Headers.Add(item.Name, item.Value.ToString());
            }
        }

        CredentialCache credentialCache = new CredentialCache
        {
            { new Uri(url), "Basic", new NetworkCredential("member", "secret") }
        };
        request.Credentials = credentialCache;

        request.ServicePoint.Expect100Continue = false;
        using (Stream stream = request.GetRequestStream())
        {
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            if (kVDatas != null)
            {
                foreach (string key in kVDatas.Keys)
                {
                    stream.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem = string.Format(formdataTemplate, key, kVDatas[key]);
                    byte[] formitembytes = Encoding.GetEncoding("UTF-8").GetBytes(formitem);
                    stream.Write(formitembytes, 0, formitembytes.Length);
                }
            }
            stream.Write(endbytes, 0, endbytes.Length);
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            return stream.ReadToEnd();
        }

    }
    catch (Exception e)
    {

        Console.WriteLine(e.Message);
        return e.Message;
    }
}

使用text形式发送multipart/form-data请求

JObject signatory = new JObject()
{
  { "content", "test content" }
};  
string boundary = "---------------------------" + timeStamp;
StringBuilder inStr = new StringBuilder();

inStr.Append("--" + timeStamp + "\r\n");
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
string formitem = string.Format(formdataTemplate, "dataString", signData["content"]);
inStr.Append(formitem);
inStr.Append("\r\n" + "--" + timeStamp + "\r\n");
formitem = string.Format(formdataTemplate, "signatory", JsonConvert.SerializeObject(signatory));
inStr.Append(formitem);
inStr.Append("\r\n" + "--" + timeStamp + "\r\n");
formitem = string.Format(formdataTemplate, "tenantType", "PERSONAL");
inStr.Append(formitem);
inStr.Append("\r\n" + "--" + timeStamp + "\r\n");
inStr.Append("\r\n" + "--" + timeStamp + "--\r\n");

上传文件

public static string HttpUploadFile(string url, string filePath, string fileName, string paramName, string contentType,
    NameValueCollection nameValueCollection)
{
    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}";
    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", paramName, fileName, contentType);
    byte[] headerbytes = 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();
    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;
        }
        return null;
    }
    finally
    {
        request = null;
    }
}

标签:string,C#,汇总,req,request,Length,HttpWebRequest,new
From: https://www.cnblogs.com/waou/p/18279622

相关文章

  • TypeScript中,如何利用数组生成一个联合类型
    本文由ChatMoney团队出品在开发中我们常常会遇到这样一个问题,代码如下:constarr=["a","b","c","d","e","f","g","h","i","j","k","l&qu......
  • IntelliJ IDEA java maven项目读取配置文件信息 java.util.ResourceBundle 方式
    一、在main目录下新建resources目录并将其设为资源文件目录  创建config.properties文件二、在pom.xml中添加下面代码 只这样打包后jar才能有配置文件<resources><resource><filtering>true</filtering><directory>src/main/......
  • ASP.NET Core 添加MIME类型
    原文链接:https://blog.csdn.net/qq_37413562/article/details/102945195ASP.NETCore添加MIME类型   FileExtensionContentTypeProviderFileExtensionContentTypeProvider和ASP.NET在web.config中添加不同,ASP.NETCore添加MIME类型需要通过FileExtensionContentTypeProvid......
  • webpack概念
    总体简单来说:Webpack通过内部的事件流机制,保证了插件的有序性Webpack底层利用了发布订阅模式,在运行过程中会广播事件Webpack插件只需要监听它所关心的事件,在特定的时机对资源做处理站在代码逻辑的角度:Webpack在编译过代码程中,会触发一系列Tapable钩子事件插件需......
  • Codeforces Round 941 (Div. 2) cf 941 div2 A~D
    每题都有AC代码在伸缩代码框请留意!!A.CardExchange-------------------------------------------题解----------------------------------选择任意K张相同的牌替换成k-1张任意的牌,也就是说只要有一组牌相同的数量大于k就可以获得最大k-1相同的其他牌,按照这个策略便可以替换掉......
  • 【打卡】003 p3 Pytorch实现天气识别
    打卡~555我的环境:●语言环境:Python ●编译器:jupyternotebook●深度学习环境:Pytorch>-**......
  • CH02_JS变量和数据类型
    第2章:JS中的变量和数据类型本章目标掌握变量的概念掌握如何使用变量掌握javascript中的数据类型课程回顾js的三种使用方式?js的注释有那些?讲解内容1.为什么要使用变量?问题:人类是靠什么要记忆(记录数据)?大脑、作笔记等问题:计算机如果要保存数据,靠什么来保存?硬件......
  • CH01_初识JavaScript
    第1章:初识JavaScript编程语言本章目标了解为什么要学习JavaScipt编程语言掌握JS的基本结构掌握JS的执行原理掌握JS的基本语法结构掌握JS的几种输出方式掌握JS的注释课程回顾什么是HTML?HTML的标签分为块级元素和行级元素,他们的区别是什么?HTML的表单元素有那些?HTML的列表......
  • C#基础不常用
    字符串格式化{0:c}货币 d2不足两位补足两位 f1根据精度显示 p以百分数显示 转义\ 空字符\0 \r\n换行 \t空格 /截断取整 stringstr01=1>2?"ok":"no"; 变量名=条件?满足条件的结果:不满足条件的结果 Parse把string转换为其他类型 console.wr......
  • LeetCode 857. Minimum Cost to Hire K Workers
    原题链接在这里:https://leetcode.com/problems/minimum-cost-to-hire-k-workers/description/题目:Thereare n workers.Youaregiventwointegerarrays quality and wage where quality[i] isthequalityofthe ith workerand wage[i] istheminimumwagee......