zoukankan      html  css  js  c++  java
  • c#Post方法封装处理

    public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
            {
                string ret = string.Empty;
                try
                {
                    if (dataEncode == null)
                        dataEncode = Encoding.UTF8;
    
                    byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                    HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                    webReq.Method = "POST";
                    webReq.ContentType = "application/x-www-form-urlencoded";
                    //webReq.ContentType = "application/json; charset=UTF-8";
    
    
                    webReq.ContentLength = byteArray.Length;
                    Stream newStream = webReq.GetRequestStream();
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    newStream.Close();
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                        var c = response.GetResponseStream();
                        StreamReader sr = new StreamReader(c, Encoding.UTF8);
                        while (sr.Peek() > 0)
                        {
                            Char[] read = new Char[256];
                            int count = sr.Read(read, 0, read.Length);
    
                            String str = new String(read, 0, count);
    
                            ret += str;
                        }
    
                        sr.Close();
                        response.Close();
                        newStream.Close();
                    }
                    catch (WebException ex)
                    {
                        //如果服务器报错(如字段不存在等异常),报500错误,此处进行获取提示信息
                        var res = (HttpWebResponse)ex.Response;
                        StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                        ret = sr.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
                return ret;
            }    
    

      

  • 相关阅读:
    C#编程技巧之钩子函数的使用——SetWindowsHookEx
    JSON(Ajax)和JsonP
    C#对象与方法
    C#数据类型
    事务处理
    面向对象之继承与多态
    C#编程语言简介
    <转>成员函数的重载、覆盖与隐藏
    视图、索引
    C#方法
  • 原文地址:https://www.cnblogs.com/a735882640/p/11049366.html
Copyright © 2011-2022 走看看