C# post 请求

发布时间:2024年01月22日
/// <summary>
/// C# post 请求
/// </summary>
/// <param name="data">body参数</param>
/// <param name="serviceUrl">请求地址</param>
/// <param name="cookie"></param>
/// <param name="dic">Headers参数</param>
/// <returns></returns>
public string Post(string data, string serviceUrl, string cookie, Dictionary<string, string> dic = null)
{
    try
    {
        string returnXml = "";
        //创建Web访问对象
        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl));
        if (!string.IsNullOrEmpty(cookie))
            myRequest.Headers.Add(HttpRequestHeader.Cookie, cookie);
        //把用户传过来的数据转成“UTF-8”的字节流
        byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
        if (dic != null && dic.Count != 0)
        {
            foreach (var item in dic)
            {
                myRequest.Headers.Add(item.Key, item.Value);
            }
        }
        myRequest.Method = "POST";
        myRequest.ContentLength = buf.Length;
        myRequest.ContentType = "application/json";
        myRequest.KeepAlive = false;
        myRequest.ProtocolVersion = HttpVersion.Version10;
        myRequest.Timeout = 100000;
        myRequest.MediaType = "application/json";
        myRequest.Accept = "application/json";

        //发送请求
        Stream stream = myRequest.GetRequestStream();
        stream.Write(buf, 0, buf.Length);

        //获取接口返回值
        //通过Web访问对象获取响应内容
        HttpWebResponse myResponse = null;
        try
        {
            myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            reader.Close();
        }
        catch (Exception ex)
        {
            string exc = ex.ToString();
        }
        finally
        {
            stream.Close();
            if (myResponse != null)
                myResponse.Close();
            if (myRequest != null)
            {
                myRequest.Abort();
            }
        }
        return returnXml;
    }
    catch
    {
        return null;
    }
}

文章来源:https://blog.csdn.net/SunGuangHuiM/article/details/135750828
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。