• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

.net 后台发起http 请求,调用接口post

武飞扬头像
满头黑发的老猿
帮助1

  public static string PostDate(string url, string content)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.Timeout = 20000;
        httpWebRequest.Method = "POST";
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        byte[] bytes = Encoding.UTF8.GetBytes(content);
        using (Stream stream = httpWebRequest.GetRequestStream())
        {
            stream.Write(bytes, 0, bytes.Length);
        }

        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        Stream responseStream = httpWebResponse.GetResponseStream();
        StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
        string result = streamReader.ReadToEnd();
        responseStream.Close();
        return result;
    }

    public static string PostMethed(string url, object obj_model, string mthod, Dictionary<string, string> headerdic = null, string contexttype = "")
    {
        string s = ObjectToJson(obj_model);
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.Method = mthod;
        if (headerdic != null && headerdic.Count != 0)
        {
            foreach (KeyValuePair<string, string> item in headerdic)
            {
                httpWebRequest.Headers.Add(item.Key, item.Value);
            }
        }

        httpWebRequest.ContentType = contexttype;
        byte[] bytes = Encoding.UTF8.GetBytes(s);
        httpWebRequest.ContentLength = bytes.Length;
        string text = "";
        try
        {
            Stream requestStream = httpWebRequest.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            string text2 = "";
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
            while ((text2 = streamReader.ReadLine()) != null)
            {
                text = text2;
            }
        }
        catch (Exception ex)
        {
            text = ex.Message;
        }

        return text;
    }

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgebfhb
系列文章
更多 icon
同类精品
更多 icon
继续加载