zoukankan      html  css  js  c++  java
  • WebRequest 对象的使用

    调用格式:

                string url = "http://localhost:26314/HttpPost.ashx?";
                string postDate = "userid=1&username=李四";
                HttpPost(url, postDate);

    c#代码:

            /// <summary>
            /// Post请求
            /// </summary>
            /// <param name="uri">请求的地址:</param>
            /// <param name="postData">参数</param>
            /// <returns></returns>
            string HttpPost(string uri, string postData)
            {
                WebRequest webRequest = WebRequest.Create(uri);
                webRequest.ContentType = "application/x-www-form-urlencoded"; // 设置请求的参数形式
                webRequest.Method = "POST";
                byte[] bytes = Encoding.UTF8.GetBytes(postData); //指定编码格式
    
                webRequest.ContentLength = bytes.Length; // 设置请求参数的长度.
    
                Stream inStream = null;
                try
                {
                    inStream = webRequest.GetRequestStream(); //取得发向服务器的流
                    inStream.Write(bytes, 0, bytes.Length);  //发送
                }
                catch (WebException ex)
                {
                    return ex.Message.ToString();
                }
                finally
                {
                    if (inStream != null)
                    {
                        inStream.Close();
                    }
                }
    
                StreamReader readStream = null;
                try
                {
                    WebResponse webResponse = webRequest.GetResponse(); // 等待返回结果
                    if (webResponse == null)
                    { 
                        return null;
                    }
                     readStream = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                    return readStream.ReadToEnd().Trim();
                }
                catch (WebException ex)
                {
                    return ex.Message.ToString();
                }
    
                finally
                {
                    if (readStream != null)
                    {
                        readStream.Close();
                    }
                }
            }

                

  • 相关阅读:
    从自然数到有理数
    付费版乐影音下载器使用方法
    Avtiviti之流程变量
    activity(工作流)初步学习记录
    IntelliJ IDEA安装Activiti插件并使用
    golang 性能测试
    Golang性能测试工具PProf应用详解
    java连接ZK的基本操作
    会员体系、积分、等级
    Flink基本概念
  • 原文地址:https://www.cnblogs.com/bweb/p/4708685.html
Copyright © 2011-2022 走看看