首页 > Web开发 > 详细

.net 发送get/post请求

时间:2017-01-12 18:28:23      阅读:14      评论:0      收藏:0      [点我收藏+]

标签:asp   cep   数字   ram   else   ive   .proto   响应   rac   

一、使用

string url = "http://www.example.com/api/exampleHandler.ashx";

var parameters = new Dictionary<string, string>();
parameters.Add("param1", "1"); 
parameters.Add("param2", "2"); 

string result = sendPost(url, parameters, "get");//调用下面定义的sendPost方法发送get请求

二、相关方法

/// <summary>
/// Http (GET/POST)
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="parameters">请求参数</param>
/// <param name="method">请求方法</param>
/// <returns>响应内容</returns>
static string sendPost(string url, IDictionary<string, string> parameters, string method)
{
    if (method.ToLower() == "post")
    {
        HttpWebRequest req = null;
        HttpWebResponse rsp = null;
        System.IO.Stream reqStream = null;
        try
        {
            req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = method;
            req.KeepAlive = false;
            req.ProtocolVersion = HttpVersion.Version10;
            req.Timeout = 5000;
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
            reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        finally
        {
            if (reqStream != null) reqStream.Close();
            if (rsp != null) rsp.Close();
        }
    }
    else
    {
        //创建请求
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));

        //GET请求
        request.Method = "GET";
        request.ReadWriteTimeout = 5000;
        request.ContentType = "text/html;charset=UTF-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

        //返回内容
        string retString = myStreamReader.ReadToEnd();
        return retString;
    }
}

/// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
static string BuildQuery(IDictionary<string, string> parameters, string encode)
{
    StringBuilder postData = new StringBuilder();
    bool hasParam = false;
    IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
    while (dem.MoveNext())
    {
        string name = dem.Current.Key;
        string value = dem.Current.Value;
        // 忽略参数名或参数值为空的参数
        if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
        {
            if (hasParam)
            {
                postData.Append("&");
            }
            postData.Append(name);
            postData.Append("=");
            if (encode == "gb2312")
            {
                postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
            }
            else if (encode == "utf8")
            {
                postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
            }
            else
            {
                postData.Append(value);
            }
            hasParam = true;
        }
    }
    return postData.ToString();
}

/// <summary>
/// 把响应流转换为文本。
/// </summary>
/// <param name="rsp">响应流对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>响应文本</returns>
static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
    System.IO.Stream stream = null;
    StreamReader reader = null;
    try
    {
        // 以字符流的方式读取HTTP响应
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        return reader.ReadToEnd();
    }
    finally
    {
        // 释放资源
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
    }
}

 

.net 发送get/post请求

标签:asp   cep   数字   ram   else   ive   .proto   响应   rac   

原文:http://www.cnblogs.com/stgp/p/6279112.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号